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 :).
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.
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