Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a 2D dynamically allocated array to a function?

I have a 2 dimensional array dynamically allocated in my C code, in my function main. I need to pass this 2D array to a function. Since the columns and rows of the array are run time variables, I know that one way to pass it is :

-Pass the rows and column variables and the pointer to that [0][0] element of the array

myfunc(&arr[0][0],rows,cols)

then in the called function, access it as a 'flattened out' 1D array like:

ptr[i*cols+j]

But I don't want to do it that way, because that would mean a lot of change in code, since earlier, the 2D array passed to this function was statically allocated with its dimensions known at compile time.

So, how can I pass a 2D array to a function and still be able to use it as a 2D array with 2 indexes like the following?

arr[i][j].

Any help will be appreciated.

like image 227
goldenmean Avatar asked Aug 05 '10 12:08

goldenmean


2 Answers

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;
}
like image 138
Arjit Avatar answered Oct 31 '22 17:10

Arjit


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);
like image 28
caf Avatar answered Oct 31 '22 19:10

caf