-1

I'm getting a strange "Segmentation fault: 11" with this simple code and can't figure it out what is the problem. I just need to dynamically declare and array with size nrows x ncolumns.

#include <stdlib.h>
#include <stdio.h>

int main()
{
    int nrows = 3;
    int ncolumns = 5;

    int **array;
    array = calloc(nrows, sizeof(int));
    for(int i = 0; i < nrows; i++)
    {
        array[i] = calloc(ncolumns, sizeof(int));
        if(array[i] == NULL)
        {
            fprintf(stderr, "out of memory\n");
            exit(-1);
        }
    }

    for(int i = 0; i < nrows; i++)
    {
        for(int j = 0; j < ncolumns; j++)
        {
            array[i][j] = 10;
            printf("%d %d: %d\n",i,j, array[i][j]);
        }   
    }
    return 0;
}
Miguel
  • 2,738
  • 3
  • 35
  • 51

1 Answers1

4

You're mixing your metaphors. You declare your array to be a block of pointers to pointers, but then allocate int sized memory blocks. You might just get away with this where the size of a pointer is the size of an int, but it's still incorrect.

The simplest option is to make it a simple 1D array that you access with row and column strides (ie, array[row*ncolumns + column]), or to use pointers more thoroughly throughout.

Note that you can't use doubled up array syntax to access this sort of dynamically allocated 2D array, as the compiler does not know the size of the inner array, and because of that, the stride of the outer array.

Gareth Pulham
  • 654
  • 4
  • 10