0

I was experimenting some basic C code that defines an int matrix with pointers.

typedef int **Matrix;

Matrix createMatrix(int lines, int columns) {
    int i, j;
    Matrix m = (Matrix) malloc(sizeof(int) * lines * columns);
    for (i = 0; i < lines; ++i) {
        for (j = 0; j < columns; ++j) {
            m[i][j] = 0;
        }
    }
    return m;
}

int main(int argc, char**argv) {
    Matrix m = createMatrix(5, 10);
    // ...
    if (m[2][3] == 20) {
        // ...
    }
    return 0;
}

However, these m[i][j] accesses are throwing segmentation faults. What's wrong here? Too many asterisks?

I was convinced that a pointer to a pointer to an int was effectively the same as a matrix.

afsantos
  • 5,178
  • 4
  • 30
  • 54
  • did you include `stdlib.h`? – Iharob Al Asimi Mar 17 '15 at 22:43
  • check some other questions on "how to allocate a 2-d array" on this site, there are many working examples – M.M Mar 17 '15 at 22:51
  • Do you know the difference between an array and a pointer? A pointer to a pointer, an array of pointers, and an array of arrays are completely different things (although the second one can be pointed to with the first one). – user253751 Mar 17 '15 at 22:57

1 Answers1

6

Your allocation of the Matrix data item assumes you're accessing it linearly with a single index. If you want to access it with two indices, e.g., m[1][1] you need to allocate each dimension:

Matrix m = malloc(sizeof(int *) * lines);

for ( int i = 0; i < lines; i++ )
    m[i] = malloc(sizeof(int) * columns);

Note also that you should not type cast malloc.

Community
  • 1
  • 1
lurker
  • 56,987
  • 9
  • 69
  • 103
  • Silly mistake. It makes sense to allocate each of the arrays individually. – afsantos Mar 17 '15 at 22:46
  • 1
    @afsantos it is actually common when someone first learns to allocate a multidimensional array. The way to look a it is `m[i][j]` is indexing `i` off of the `m` address, and indexing `j` off of the `m[i]` address. – lurker Mar 17 '15 at 22:47