I\'m trying to allocate a 2d array in a C program. It works fine in the main function like this (as explained here):
#include
#include
Here is your function, fixed:
int malloc2d(int *** grid, int nrows, int ncols){
int i;
*grid = (int**)malloc( sizeof(int *) * nrows);
if (*grid == NULL){
printf("ERROR: out of memory\n");
return 1;
}
for (i=0;i<nrows;i++){
(*grid)[i] = (int*)malloc( sizeof(int) * ncols);
if ((*grid)[i] == NULL){
printf("ERROR: out of memory\n");
return 1;
}
}
printf("Allocated!\n");
return 0;
}
int main(int argc, char ** argv)
{
int ** grid;
malloc2d(&grid, 10, 10);
grid[5][6] = 15;
printf("%d\n", grid[5][6]);
return 0;
}
Note the function now recieves an int***
and you pass the address of your int**
to the function. The function then dereferences the int***
to put the address of the allocated memory block in it.