Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 2D arrays in C like argv of main

Tags:

c

pointers

I am learning passing 2D arrays to functions in C and learned that I can receive 2D array in the function as following:

  1. void test(char a[5][10])
  2. void test(char (*a)[10])

Above declarations work for me but looking on **argv parameter of function main I thought of changing my function to void test(char **a). But this does not work correctly. I do not understand why. Please explain.

Here is my code

#include<stdio.h>

int main(int argc, char **argv){
    char multi[5][10] = {
                         {'0','0','2','3','4','5','6','7','1','9'},
                         {'a','b','c','d','e','f','g','h','i','j'},
                         {'A','B','C','D','E','F','G','H','I','J'},
                         {'9','8','7','6','5','4','3','2','1','0'}, 
                         {'J','I','H','G','F','E','D','C','B','A'}
                        };
    test(multi);
    return 0;
}

void test(char (*a)[10]) // void test(char **a) does not work
{
    printf("\n a[2][1] is: %d",*(*(a + 2)+1));
}
like image 334
Bhaskar Avatar asked Dec 21 '22 03:12

Bhaskar


2 Answers

An array name when passed to a function will decay to the value of the address of its first element, and its type will be a pointer to that element type. Since the type of multi[0] is a char[10], then multi will decay pointer to char[10].

main() receives an array of pointers to char in its second parameter, which is why argv can be char **argv or char *argv[].

like image 98
jxh Avatar answered Jan 04 '23 00:01

jxh


For multidimensional arrays, rows are stored in continuous memory locations. That's why we need to pass the number of columns, i.e., to calculate the number of items to jump over to get to a specific row.

In case of pointer to pointers, rows are stored in arbitrary memory locations. You cannot find the location of a row given the pointer to the first row and an index. In this case, you need as much pointers as you have rows.

In short, the two versions of your function arguments assume different memory layouts and as such, they are incompatible.

like image 35
perreal Avatar answered Jan 04 '23 01:01

perreal