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?
CodePudding user response:
Those are both arrays of pointers, and pointers hold addresses. int *numbers[] = { {1,2,3}, {4,5,6} }
can't work, you are attempting to initialize an array of pointers with a 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 int
s, which is what that type can hold, in this case the initial element of an array of int
:
//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] };
// or simply
//int *numbers[] = { a, b };
Note that unlike the string literals, these arrays have no sentinel value, for you to safely navigate inside the bounds of each array you must keep its size.
CodePudding user response:
int *numbers[]
It is not "ragged array" only an array of pointers.
int *numbers[] = { (int[]){1,2,3}, (int[]){4,5,6,7,8} };
In this example it has two elements having type pointer to int. Those pointers hold the reference of the first element of the arrays used to initialize it.