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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With