Passing a multidimensional array to a C function

I am having problems passing a multidimensional array to a function from C. Both in typedef and that there must be an argument.

Currently, my def function looks like this:

int foo(char *a, char b[][7], int first_dimension_of_array);

I declare an array as follows:

char multi_D_array[20][7];

When I try to call a function as follows:

foo(d, multi_D_array, 20);

I get a warning that the second argument to the function is an incompatible pointer type. I tried many of the options that I saw on the Internet, but still can't get it right. Also, when using GDB, I find that only the first array of the 2D array is transmitted. Feedback from what I am doing wrong will be greatly appreciated.

+3
source share
6 answers

: .

, :

#include <stdio.h>

int foo(char b[][7])
{
    printf("%d\n", b[3][4]);
    return 0;
}

int main(int argc, char** argv)
{
    char multi_d_arr[20][7];
    multi_d_arr[3][4] = 42;
    foo(multi_d_arr);
    return 0;
}

- , gcc -Wall. , , . .

, , 2-D ? :

char** array2d = malloc((MAX_i+1)*sizeof(char*));
for ( i = 0; i < (MAX_i+1); i++ )
{
    array2d[i] = malloc((MAX_j+1)*sizeof(char));
}

, , , , - array2d[MAX_i][MAX_j].

, :

for ( i = 0; i < (MAX_i+1); i++ )
{
    free(array2d[i]);
}
free(array2d);

, , , array2d[x][y] - . , array2d - , array2d[i].

? , , . , , for. , int main(int argc, char** argv) . argv - . strlen(), .

? . , , :

int foo(char** ar2d, const unsigned int size);

:

char** somearray;
/* initialisation of the above */

foo(ar2d, thesizeofar2d);

/* when done, free somearray appropriately */

, (, const unsigned int size) , .

+5

, , C gcc.

?

+1

, .

char[20][7] char[][7]

.

" 2D-", ( ). 7 GDB, GDB 7 .

0

C99 , . . , , .

#include <stdio.h>

int foo(char *a, int fdim, char b[fdim][7]){

    printf("b[19][6] = %d\n", b[19][6]);
    return 0;
}

int main(){
    char d[10];
    char multi_D_array[20][7];
    int x, y;

    for (x = 0 ; x < 7 ; ++x){
        for (y=0 ; y < 20 ; ++y){
            multi_D_array[y][x] = y + x;
        }
    }
    foo(d, 20, multi_D_array);
}

++, , (, , ) C.

0

, C/++ . .

-2

Source: https://habr.com/ru/post/1786557/


All Articles