Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from std::vector<> to a double pointer?

I was wondering out of curiosity if it is possible to cast a std::vector<> to a double pointer.

I've never had an issue passing a std::vector as a pointer in this fashion:

std::vector<char> myCharVector;
myCharVector.push_back('a');
myCharVector.push_back('b');
myCharVector.push_back('c');
char *myCharPointer = &myCharVector[0];

So I was curious if it was possible to assign the address of the pointer in a similar way to this:

char *myPointer = "abc";
char **myDoublePointer = &myPointer; 

I've tried:

char **myDoublePointer = (char**)&myCharVector;

But it doesn't work. Is there any way of achieving this?

like image 692
kbirk Avatar asked Dec 06 '22 13:12

kbirk


2 Answers

You already know that &myCharVector[0] is a pointer to char. So if you store it in a variable:

char *cstr = &myCharVector[0];

then you can take the address of that variable:

char **ptrToCstr = &cstr;

But simply dereferencing twice like this:

char **ptrToCstr = &(&myCharVector[0])

is invalid because the value (&myCharVector[0]) isn't stored in memory anywhere yet.

like image 136
japreiss Avatar answered Dec 09 '22 02:12

japreiss


In C++11, you can do:

char *myCharPointer = myCharVector.data();

But you cannot take the address of the return value of data() because it does not return a reference to the underlying storage, just the pointer value.

If the purpose is to be able to change what the pointer is pointing to, then you may really want a pointer to a vector, rather than a pointer to a pointer to a char. But, the STL doesn't let you change the underlying pointer within the vector itself without going through the regular vector APIs (like resize or swap).

like image 40
jxh Avatar answered Dec 09 '22 02:12

jxh