-3

'ptrArrMain' is a pointer array that contains two pointer arrays (ptrArr1 and ptrArr2). I have a string ab = "ab". The address of ab[1] (i.e the address of 'b') is stored in the element ptrArr1[1]. ptrArr1[0] (i.e the address of 'a') is assigned to ptrArrMain[0].

How do I get the address of ab[1] using only the ptrArrMain array? I do not wish to use any STLs or precoded functions. I am doing this exercise to enhance my understanding of pointers. Thank you.

int main()
{

    string ab = "ab";
    string cd = "cd";

    char **ptrArrMain = new char*[2];
    char **ptrArr1 = new char*[ab.length()];
    char **ptrArr2 = new char*[cd.length()];

    ptrArr1[0] = &ab[0];
    ptrArr1[1] = &ab[1];

    ptrArr2[0] = &cd[0];
    ptrArr2[1] = &cd[1];

    ptrArrMain[0] = ptrArr1[0];
    ptrArrMain[1] = ptrArr2[0];

    cout << &ab[1] << endl;

    //  TODO
    //  Get the address of ab[1] using 'ptrArrMain'. 
    //  Do not use any other array.*/

}

I think this should be possible, because ptrArrMain[0] contains the address of the first element of "ab". With the address of the first element of "ab", I should be able to get the address of ab[1] by incrementing (or some other way) the address of ab[0] which is in ptrArrMain[0].

Robin Alvarenga
  • 321
  • 2
  • 14

1 Answers1

1

When I run your current code, with the using namespace std directive, and importing the iostream and string standard libraries I get the following result:

 > g++ test.cpp -o test
 > ./test
 b

Why is this? Well if you look at your code, you'll notice that ab is of type std::string (which is a standard library type). In the documentation we find that using the [] operator on a string is actually an overloaded operation (ie. it calls a method), which returns a reference to a char. If you attempt to get the address of the reference, you get the reference itself, which is why b is printed.

If you want to get the addresses of the underlying strings you should use C-style strings aka character arrays. You can then access the underlying arrays using array subscripts or pointer arithmetic.

    char ab[3] = "ab";
char cd[3] = "cd";

char **ptrArrMain = new char*[2];
char **ptrArr1 = new char*[strlen(ab)];
char **ptrArr2 = new char*[strlen(cd)];

ptrArr1[0] = &ab[0];
ptrArr1[1] = &ab[1];

ptrArr2[0] = &cd[0];
ptrArr2[1] = &cd[1];

ptrArrMain[0] = ptrArr1[0];
ptrArrMain[1] = ptrArr2[0];


cout << (void *)&ab[1]  << endl;
cout << (void *)(ptrArrMain[0] + 1) << endl;
cout << (void *)(*ptrArrMain + sizeof(char)) << endl;

Which will output 3 identical memory addresses.

You should also be careful printing addresses of strings as cout will interpret them as strings themselves.

jdrd
  • 159
  • 7
  • Great thanks! I should've mentioned that I was using 'string' from the standard library. Looks like converting the string to a char array is the way to go for my experiment. – Robin Alvarenga Nov 20 '18 at 20:14