How to pass a 2D dynamically allocated array to a function?
See the code below. After passing the 2d array base location as a double pointer to myfunc()
, you can then access any particular element in the array by index, with s[i][j]
.
#include <stdio.h>
#include <stdlib.h>
void myfunc(int ** s, int row, int col)
{
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++)
printf("%d ", s[i][j]);
printf("\n");
}
}
int main(void)
{
int row=10, col=10;
int ** c = (int**)malloc(sizeof(int*)*row);
for(int i=0; i<row; i++)
*(c+i) = (int*)malloc(sizeof(int)*col);
for(int i=0; i<row; i++)
for(int j=0; j<col; j++)
c[i][j]=i*j;
myfunc(c,row,col);
for (i=0; i<row; i++) {
free(c[i]);
}
free(c);
return 0;
}
If your compiler supports C99 variable-length-arrays (eg. GCC) then you can declare a function like so:
int foo(int cols, int rows, int a[][cols])
{
/* ... */
}
You would also use a pointer to a VLA type in the calling code:
int (*a)[cols] = calloc(rows, sizeof *a);
/* ... */
foo(cols, rows, a);