Just learning C, so bear with me. I understand that char *argv[]
is an array whose elements are pointers to strings. So, for example:
char *fruits[] = {"Apple", "Pear"};
represents a "ragged array" of char
arrays (i.e. a two-dimensional array whose rows have different lengths). So far, so good.
But when I try to abstract this to int types, it does not seem to work.
int *numbers[] = { {1,2,3}, {4,5,6} };
I get the following warning from the GCC compiler:
warning: braces around scalar initializer.
Can someone help me wrap my brain around this?
int *numbers[] = { {1,2,3}, {4,5,6} }
can't work, you are attempting to initialize elements of an array of pointers with lists of integers.
To initialize an array of pointers you need to provide the addresses that point to the desired values, i.e. you must initialize each element of the pointer array with addresses of the int
s you want them to point to, in this case the initial element of an array of int
so that you can have access to the beginning of the array and thus to the rest of it via indexing:
//have 2 flat arrays of int
int a[] = {1, 2, 3};
int b[] = {4, 5, 6};
// make the array of pointers point to its initial elements
int *numbers[] = { &a[0], &b[0] };
// access
printf("%d", numbers[1][1]); // 5
You could also use:
int *numbers[] = { a, b };
Why? Because when you use an array name in an expression, for example you pass it as argument of a function or an initializer list like the above one, it decays to a pointer to its first element.
char *fruits[] = {"Apple", "Pear"};
works fine because string literals have type char[]
generally, e.g. "Apple"
has type char[6]
, so when you use them in the initializer list expression the same decay process occurs, and you'll end up with a pointer to the first element of the nul terminated array of chars.
Note that unlike the above string literals (which all end with a nul byte \0
), the int
arrays have no sentinel value, unless you establish one, otherwise for you to safely navigate inside the bounds of each array you must keep track of its size.