# C - allocating a matrix in a function

I am trying to allocate a matrix using a function that takes its dimensions and a triple pointer. I have allocated an int** (set to NULL) and I am passing its address as the function's argument. That gives me a mem access violation for some reason.

void allocateMatrix(int ***matrix, int row, int col) { int i; if((*matrix = (int**)malloc(row * sizeof(int*))) == NULL) { perror("There has been an error"); exit(EXIT_FAILURE); } for(i = 0; i < row; ++i) { if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL) { perror("There has been an error"); exit(EXIT_FAILURE); } } } /* main.c */ int** matrix = NULL; allocateMatrix(&matrix, MATRIX_ROW, MATRIX_COL); //error

## Answers

You need to change

if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)

to

if(((*matrix)[i] = (int*)malloc(col * sizeof(int))) == NULL) // ^ ^

You need to dereference matrix before using the array subscript. *matrix[i] is equivalent to *(matrix[i])

It's a problem of operator precedence. In

if ((*matrix[i] = (int*)malloc( ... ))

the default precedence is *(matrix[i]), while you should use (*matrix)[i].

I would still recommend to allocate the matrix as a contiguous array instead as a array of pointers to arrays.