Reputation: 5534
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..
Upvotes: 0
Views: 1414
Reputation: 399743
There's no way for C to know how your indexing is supposed to work: there's no information that associates the number of columns (col
) with myArray
. When you do myArray[i][j]
with myArray
declared as int * *
, C will first evalutate myArray[i]
, i.e. read the i:th value of myArray
as if it were an integer pointer, which it isn't in your case. It will then index j
from that invalid value, likely generating the segmentation fault (at least causing undefined behavior).
When doing it manually like that, you have two choices:
myArray[i][i]
with myArray[i * cols + j]
.The latter uses less memory and (way) less memorhy allocations, which is nice. Of course the indexing can be a bit awkward.
Upvotes: 5
Reputation: 2068
You can allocate dynamic arrays like this. No malloc
necessary.
{
printf("rows = ");
scanf("%d", &rows);
printf("columns = ");
scanf("%d", &cols);
int my_array[rows][cols];
}
To zero the new array:
memset(my_array, 0, rows*cols*sizeof(int));
Upvotes: 0
Reputation: 2328
Try doing it like this.
table = malloc(row*sizeof(int *));
for(i = 0; i<row; i++)
table[i] = malloc(col * sizeof(int));
Upvotes: 2