#include
using namespace std;
void foo( char ** vec) {
*vec = new char[10];
*vec[0] = 'a';
*vec[1] = 0;
}
int main()
{
char * ptr;
foo(&ptr);
cout << ptr;
system("pause");
return 0;
}
There's an order of operator issue here on the dereferencing of *vec[] . Surround *vec with parenthesis and it will work. Below is a modified version with a couple of other minor changes too. See precedence table here where array subscripting is at level 1 and dereference is at level 2.
Here is a fix:
#include
using namespace std;
void foo( char ** vec) {
*vec = new char[10];
(*vec)[0] = 'a';
(*vec)[1] = 0;
}
int main(int argc, char** argv)
{
char * ptr;
foo(&ptr);
cout << ptr << endl;
system("pause");
return 0;
}
But this is ugly. We can make the code cleaner and clearer to read and
do ourself (or whoever) a favor by creating a new pointer in cases like this.
We spare ourself - and anyone who reads your code - the confusion.
Here is a better version of the function:
void foo( char ** vec) {
*vec = new char[10];
char* str = *vec;
str[0] = 'a';
str[1] = 0;
}