Why can't I point a char** to array of C strings??
int main(int argc, char *argv[]) {
char* c1[] = {"Hey","Hello"};
printf("%s",c1[1]);
} //works fine
vs
int main(int argc, char *argv[]) {
char** c1 = {"Hey","Hello"};
printf("%s",c1[1]);
} //error
I think the confusion here stems from the belief that {"Hey","Hello"}
is an array. It's not. It's not an object at all. It's just a special initializer syntax that can be used to initialize an array. You can't use it to initialise a char**
because a char**
is a pointer, not an array. It doesn't automatically create an array object that you can convert to a pointer.
Perhaps you were thinking of it like a [...]
list in Python or a { ... }
object in JavaScript. It's not like those at all. Those expressions actually create objects of that type and can be used anywhere in an expression that can take those objects. The syntax we're using in C++ is just an initialization syntax.
For example, you could do this:
const char* array[] = {"Hey","Hello"};
const char** p = array;
You, however, cannot do something silly like this:
std::cout << {"Hey", "Hello"}[1];
Here we have actually created the array object in which the pointers will be stored. Only then can we convert that array to a const char**
.
change to
char** c1 = (char *[]){"Hey","Hello"};
Why can't I point a
char**
to array of C strings?
As you said, c1
is an array. So you have to declare it as an array of pointers to char
.
Since "Hey"
and "Hello"
are string litterals, each c1[i]
string is pointing to an anonymous string. That's why you can use pointers to char
instead of arrays of char
.
To make an array of pointers to char
, however, you can't use a char **
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With