Home > Blockchain >  why I am not able to initialize array of pointers providing 2d array
why I am not able to initialize array of pointers providing 2d array

Time:07-04

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?

CodePudding user response:

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].

CodePudding user response:

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.

  • Related