I am learning C and I tried to allocate memory for a 2D array (the dimensions of the array I get them from the user), but I get a segmentation fault after I try to init it. My code is this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("give the dimensions!\n");
int row,col,i,j;
int **myArray;
printf("\nrows = ");
scanf("%d", &row);
printf("columns = ");
scanf("%d", &col);
myArray = malloc(row*sizeof(*myArray) + col*sizeof(**myArray));
printf("Init the array: \n");
for (i = 0; i < row; i++)
{
for (j = 0; j <col ; j++)
{
scanf("%d", &myArray[i][j]);
}
}
return 0;
}
If I change the array as myArray[2][2]
and omit the malloc statement it works fine..