Search code examples
cpointersmultidimensional-array

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].

Solution

  • 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;
    }