For the array to persist in memory, it either needs to be declared static
or it should be explicitly allocated using malloc
or calloc
(each solution has functionality implications--i.e. the static
version will be overwritten the next time the function is called, and the allocated version needs to be explicitly freed later to avoid memory leaks).
Note that pointers and arrays are not the same thing in C, and since you're dealing with dynamic allocation in the malloc
case, you'll be working with pointers. Referencing array elements using these pointers will be functionally the same as referencing array elements, so you shouldn't notice a difference once the array has been created.
Here is an example that allocates, populates and returns a 2D array using a single malloc
(both for the sake of efficiency, and to allow the use of a single free
for deallocation):
int **get2dArray(int rows, int cols)
{
int **array2d;
int i, j, offset;
int *gridstart;
offset = rows * sizeof(int *);
array2d = malloc( offset + rows*cols*sizeof(int) );
/* Demote to char for safe pointer arithmetic */
gridstart = (int *)((char *)array2d + offset);
for ( i = 0; i < rows; i++ ) {
/* Point to the proper row */
array2d[i] = gridstart + i*cols;
/* Populate the array -- your code goes here */
for ( j = 0; j < cols; j++ ) {
array2d[i][j] = i*cols + j;
}
}
return array2d;
}
int main ( int argc, char **argv )
{
int **testarray;
testarray = get2dArray( 10, 100 );
/* Verify that addressing and population went as planned */
printf( "%d %d %d %d %d %d\n", testarray[0][0], testarray[2][55],
testarray[4][98], testarray[5][0], testarray[7][15],
testarray[9][99] );
free(testarray);
return 0;
}
There are many other ways to do this, but this demonstrates a function that will return a 2D pointer "array".