Question

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

Was it helpful?

Solution

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:

  • Make it "jagged", where each row has its own pointer to that row's elements. This is what @bgamlath suggests in his answer.
  • Do the indexing yourself, by replacing 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.

OTHER TIPS

Try doing it like this.

  table = malloc(row*sizeof(int *));
  for(i = 0; i<row; i++)
    table[i] = malloc(col * sizeof(int));

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top