Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array of pointers to pointers

Tags:

arrays

c

pointers

This example works fine:

static char *daytab[] = {
    "hello",
    "world"
};

This doesn't:

static char *daytab[] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

The way I see it is that the first example creates an array that is filled with pointers to the two string literals (which themselves are arrays). The second example, IMO, should be identical - create an array and fill it with pointers to the two char arrays.

Could someone explain to me why the second example is wrong?

P.S. You could probably write it like this (haven't tested it):

static char a[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static char b[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static char *daytab[] = {
    a,
    b
};

But that looks like too much work :).

like image 532
Ree Avatar asked Dec 23 '22 12:12

Ree


1 Answers

This:

{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

Is just an array initializer. It doesn't itself create an array. The first example, when you assigned a string literal to a pointer, DID create those strings in static storage (hidden to you), and then just assigned the pointers to them.

So basically, there is no way to initialize your char* with the array initializer. You need to create an actual array, and assign those numbers to it. You would have to do something like:

char a[][] = { {32, 30, 0}, {34, 32, 33, 0} }; // illegal

But that is illegal.

You need to build the array separately and assign them into an array like your last example.

like image 64
Greg Rogers Avatar answered Jan 17 '23 00:01

Greg Rogers