Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of pointer declaration

Tags:

arrays

c

pointers

i need a few explanation on array of pointers and more precisly, how to declare them.
Take a look at this code:

main()
{
    int array[] = {5, 4, 2};
    int array2[] = {6, 8};
    int* int_arrays[2] = {array, array2}; // It works!

//  int* int_arrays2[2] =
//  {
//      {5, 4, 2},
//      {6, 8}
//  };
//
    int i, j;
    for(i = 0; i < 2; i++) 
    {
        for(j = 0; j < 3; j++) // This loop print a garbage value at the end, no big deal.
                printf("%d\n", int_arrays[i][j]);
    }
}

For me the commented declartation means the same as the one above. But it doesn't work.
The visual studio C compiler give me those indications:
error: too many initializers.
warning: int* differs in levels of indirection from int.

I guess it means that int array[] = {5, 4, 2} is something valid to assign to an int*
while {5, 4, 2} is not.
Could you show me a way to delcare my array of pointer correctly?

like image 654
aurelienC Avatar asked Dec 24 '22 11:12

aurelienC


1 Answers

An array initializer is not a object and so you can't have a pointer to the start of such and object. If you have at least C99, you could do

int* int_arrays2[2] =
{
     (int[]){5, 4, 2},
     (int[]){6, 8}
};

These are so-called "compound literals" that are objects, and thus in this case covert to the pointer type that you need.

like image 78
Jens Gustedt Avatar answered Jan 10 '23 22:01

Jens Gustedt