Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char** vs char* c[] for accessing a string array

Tags:

c++

c

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
like image 637
tez Avatar asked Apr 10 '13 12:04

tez


3 Answers

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**.

like image 161
Joseph Mansfield Avatar answered Sep 21 '22 01:09

Joseph Mansfield


change to

char** c1 = (char *[]){"Hey","Hello"};

like image 37
BLUEPIXY Avatar answered Sep 18 '22 01:09

BLUEPIXY


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 **.

like image 23
md5 Avatar answered Sep 21 '22 01:09

md5