1
votes

enter image description here

int *p = ( int[] ){ 1, 2, 3, 4 };

Doing this I am able to initialize a anonymous array to a pointer p. In a similar way I want to assign arrays of array (i.e. probably 2D array) in array of pointers. And so I have tried the following code:

int *p[]= (int [][3]) { {1,2,3},{10,20,30} };

But it goes wrong, anyway if I assign it to a pointer to whole Array( as int (*p)[]= (int [][3]) { {1,2,3},{10,20,30} }; ) it works fine. I am in confused that if a pointer can get assigned a anonymous array why the array of pointers could not get assigned to 2d array?

2
Please elaborate "it goes wrong" and provide a minimal reproducible example each for both described cases. Also pleas explain what you intend to do this way. I suspect that there is a better way. Compare meta.stackexchange.com/questions/66377/what-is-the-xy-problem - Yunnosch
If X is a type, then an array of X decays to a pointer of X. Now say X is array-of-Y. An array of X still decays to a pointer to X, that is, a pointer to an array-of-Y. It does not decay to an array of pointers to anything, nor to a pointer to a pointer to anything. - n. 1.8e9-where's-my-share m.

2 Answers

1
votes

int *p[] is an array of pointers, not a pointer to an array.

You'll need to do:

int (*p)[3]= (int [][3]) { {1,2,3},{10,20,30} };

The reason why is that an array, whenever used in an expression, decays into a pointer to the first element. So no matter the array type, your pointer will need to correspond to the pointer to the first element.

In case of an int[], the element type is int and a pointer to it would be int*.

In case of an int[][3], the element type is int[3] and a pointer to it would be int (*p)[3].

1
votes

The compound literal

(int [][3]) { {1,2,3},{10,20,30} };

has the type

int [2][3]

i.e. array of 2 elements, each consisting of 3 int elements.

When used in the line

int *p[]= (int [][3]) { {1,2,3},{10,20,30} };

the array will decay to a pointer to the first element. This pointer will therefore have the type "pointer to array of 3 int elements`.

However, you cannot assign this data type to p, because the types are different. You declared p as an array of pointers. That is why your code is not working.

If you want p to be an array of pointers in which every pointer points to its array of int elements, then you will need to use several compound literals, one for each of these arrays:

int *p[] = {
    ( int[] ){  1,  2,  3,  4 },
    ( int[] ){  5,  6,  7,  8 },
    ( int[] ){  9, 10, 11, 12 }
};

Here is a small test program:

#include <stdio.h>

int main( void )
{
    int *p[] = {
        ( int[] ){  1,  2,  3,  4 },
        ( int[] ){  5,  6,  7,  8 },
        ( int[] ){  9, 10, 11, 12 }
    };

    printf( "%d\n", p[1][2] );
}

This program has the output 7.