Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguity in 2d array declaration in C

I have defined array in the following formats, but apparently the program works fine only in CASE B.

CASE A:

int **M1;
M1 = (int **)malloc(m * sizeof(int *));
for (int i=0; i<m; i++){
    M1[i] = (int *)malloc(d * sizeof(int));
} 

CASE B:

int (*M1)[m] = malloc(sizeof(int[m][d]));

I am getting a segmentation error in CASE A. What could be the reason?

like image 219
re3el Avatar asked Aug 13 '15 08:08

re3el


1 Answers

The following code compiles without error or warning in gcc compiler,

    int **M1,i;
    M1 = (int **)malloc(5 * sizeof(int *));
    for (i=0;i<5;i++){
        M1[i] = (int *)malloc(2 * sizeof(int));
    }
    M1[0][0]=111;
    M1[0][1]=222;
    printf("\n%d %d",M1[0][0],M1[0][1]);

Gives 111 222 as output.

The problem might be some where else in your code.

like image 93
Deepu Avatar answered Oct 02 '22 15:10

Deepu