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

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

-Remove row and column variables and pointer to this array element [0] [0]

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

then in the called function, refer to it as a "flattened" 1D array, for example:

ptr[i*cols+j]

But I don’t want to do this because it will mean a lot of changes in the code, because previously the 2D array passed to this function was statically distributed with its sizes known at compile time.

So, how can I pass a 2D array to a function and still use it as a 2D array with two indices, such as:

arr[i][j].

.

+5
7
#include <stdio.h>
#include <stdlib.h>
void doit(int ** s , int row , int col ) 
{
    for(int i =0 ; i <col;i++){
            for(int j =0 ; j <col;j++)
                printf("%d ",s[i][j]);
            printf("\n");
    }
}
int main()
{
    int row =10 , col=10;
    int ** c = (int**)malloc(sizeof(int*)*row);
    for(int i =0 ; i <col;i++)
        *(c+i) = (int*)malloc(sizeof(int)*row);
    for(int i =0 ; i <col;i++)
            for(int j =0 ; j <col;j++)
                c[i][j]=i*j;
    doit(c,row,col);
}

, , ....

+7

C99 (, GCC), ​​:

int foo(int cols, int rows, int a[][cols])
{
    /* ... */
}

VLA :

int (*a)[cols] = calloc(rows, sizeof *a);
/* ... */
foo(cols, rows, a);
+2

, . , , regexp search'n'replace .

, AA(arr,i,j) ( Access), arr - .

+1

, , , - . , , " ", () .

array-of-T, , ( ) ; - .

, C FAQ.

+1

C (, ) - 2D-. 1.2 " 2D-" convert_matrix().

, , . .

0

2- C . ya go:

void with_matrix(int **matrix, int rows, int cols) {
    int some_value = matrix[2][4];
}

int main(int argc, char **argv) {
    int **matrix;
    ... create matrix ...
    with_matrix(matrix, rows, cols);
}
0
int cols = 4;
    int rows = 3;
    char** charArray = new char*[rows];
    for (int i = 0; i < rows; ++i) {
        charArray[i] = new char[cols];
    }

    // Fill the array
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            charArray[i][j] = 'a';
        }
    }

    // Output the array
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            cout << charArray[i][j];
        }
        cout << endl;
    }
0

All Articles