Reputation: 814
I have some problems at understanding char pointers. Let's say there is the following method declaration (sorry but I don't have the implementation of the method, I hope it's enough to explain my problem):
short GetInfo(char **param1, char **param2);
I tried to call it 2 different ways:
// 1. When I call it this way it works
char param1_val[20];
char *param1_ptr = param1_val;
char param2_val[20];
char *param2_ptr = param2_val;
GetInfo(¶m1_ptr, ¶m2_ptr);
// 2. When I call it that way I get an 'access violation exception'
char *param1_array[20];
char *param2_array[20];
GetInfo(param1_array, param2_array);
I thought
char param1_val[20];
char *param1_ptr = param1_val;
is the same as
char *param1_array[20];
But it seems they are different. Is there a way how I could get my second case work? Or did I mix things up and I have to do it like in case 1?
Upvotes: 0
Views: 5955
Reputation: 1401
The probable reason for declaring GetInfo
as a function taking a char**
is that it outputs a char*
, so it is probably expected to be used more like so:
//short GetInfo(char **param1, char **param2);
char *ptr1=nullptr;
char *ptr2=nullptr;
GetInfo(&ptr1,&ptr2);
if(ptr1)
std::cout<<*ptr1<<std::endl;
//etc
To really understand pointers and arrays, find C documentation on the subject. In C++, they are backwards compatible with C. However, in C++ it is better to work at higher level, e.g. use STL instead of coding in C style.
Upvotes: 2
Reputation: 36483
I thought
char param1_val[20];
char *param1_ptr = param1_val;
is the same as
char *param1_array[20];
They're not the same.
char param1_val[20];
char *param1_ptr = param1_val;
Declares an array of 20 chars param1_val
and declares & assigns param1_ptr
to the memory location of param1_val[0]
, so ¶m1_val[0]
.
char *param1_array[20];
Declares an array of 20 char pointers param1_array
that still all point to garbage locations.
I'm assuming that GetInfo
is dereferencing the pointers in your param1_array
and that causes the access violation as trying to read from a random memory address is not something you want to do.
Upvotes: 4