C++ Pointer to String Array

Spread the love

string var[5] friends = {“Amy”,”John”,”Joyce”,”Deszrene”,”Samson”};
string *ptr;

ptr = &friends[2]; // pointer to the 3rd position in array

std::cout << “Value of friends position 3 = ” << *ptr << std::endl;

C++ string pointers to specific positions in the string array

Other good articles on c++ pointers to string arrays are over here.

Feel Free to Copy the code below and test it online or on your local C++ Compiler/Editor

// C++ pointer to String Array
#include <iostream>
using namespace std;
int main () {
    string *ptr;
    string *ptr1;
    string miniAlpha[5] = {"Mary","had","a","little","lamb"};
    ptr = &amp;miniAlpha[0];
    ptr1 = &amp;miniAlpha[1];
    cout << "Value of miniAlpha position 0 = " << *ptr << endl;
    cout << "Value of miniAlpha position 1 = " << *ptr1 << endl;

   return 0;

C++ Pointer to String Array

Point that pointer to an Address of the same type

This magic happens in line 9 and 10 when we make the 2 pointers equal to the beginning address of the string array.
Just remember a pointer points to an address and since the pointer has a type, that same pointer string pointer knows that if the programmer is smart he/she has pointed to a string. Yes, it is possible to get a pointer to point to something that it shouldn’t but let’s not go there yet.

Value of miniAlpha position 0 = Mary

Value of miniAlpha position 1 = had

Homework — Pointing to a position in the String Array

  • 1) The last example above is super short. Please memorize
  • 2) From memory rewrite the code above into your c++ compiler/editor
  • 3) Add a 3rd pointer and point it to the ‘Lamb’ in the array
  • 4) Add a 3rd cout statement and refer to the 3rd pointer

Next Lesson 10, Vectors & Arrays