C is willing to automatically size, allocate, and initialize arrays for you. With one exception, however, there is no way to automatically initialize a pointer that points to some other array.
Here is automatic sizing and allocation of an array:
int a[] = {1, 2, 3};
The brackets []
are empty -- you don't have to explicitly specify the size -- because the compiler can see from the initializer that the array should have size 3.
Here is another example, using char
:
char s1[] = {'H', 'e', 'l', 'l', 'o', 0};
Here is a much more convenient shortcut form:
char s2[] = "world";
Here is the exception I was talking about:
char *s3 = "hidden";
In this case, the compiler allocates a hidden, unnamed array containing the string "hidden"
, then initializes s3
to point to it. This is just about perfectly equivalent to the more explicit setup
char a2[] = "hidden";
char *s3a = a2;
except for the visibility of the intermediate array a2
.
Putting all this together, you can initialize an array of pointers to char
like this:
char *strarray[] = { "Hello", "world" };
This is equivalent (again, except for the visibility of the actual arrays holding the strings) to the more explicit
char a3[] = "Hello";
char a4[] = "world";
char *strarray2[] = { a3, a4 };
But you can not directly do anything along the lines of
char **dynstrarray = { ... };
The reason you can't do it is because dynstrarray
is fundamentally a pointer, and there's no general mechanism in C to automatically allocate something for a pointer like this to point to. Again, the only time C will automatically allocate something for a pointer to point to is the special case for pointer to char
, as demonstrated by s3
above.
So if you want to initialize a pointer like dynstrarray
, your only choice is to do it explicitly, yourself. You could initialize it to point to an array of pointers to char
that you had already constructed, like this:
char a3[] = "Hello";
char a4[] = "world";
char *strarray2[] = { a3, a4 };
char **dynstrarray[] = strarray2;
Or, more commonly, you would use malloc
to dynamically allocate some memory for dynstrarray
to point to. In that case (but only in that case) you would also have the option of resizing dynstrarray
later, using realloc
.