Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Using a n+1 dimentional array as a n dimention array parameter

My question is, when you have an array tab[a][b][c], are you allowed to use tab[a] as a parameter array[b][c]?

Here is an example:

void function(int tab[5][6])
{
    tab[4][3]++;
}

int main()
{
    int tab[9][5][6];
    for (int i=0;i<9;i++)
    {
        function(tab[i]);
    }
    return 0;
}
like image 527
Speedphoenix Avatar asked Nov 17 '25 20:11

Speedphoenix


1 Answers

when you have an array tab[a][b][c], are you allowed to use tab[a] as a parameter array[b][c]?

Yes


int tab[9][5][6]; is type array 9 of array 5 of array 6 of int.

tab[i] is type array 5 of array 6 of int.`

When code calls function(tab[i]), tab[i] is converted to the address of the first element. In this case, that is &tab[i][0], this is of type pointer to array 6 of int.

void function(int tab[5][6]) operates the same as void function(int (*tab)[6]). IOWs, the function expects a pointer to array 6 of int. The 5 is advisory to coders, but not functionality useful to code.

Good: the function call provides the expected type.

tab[4][3]++; operates on the tab[4][3]. The 4 in says to use the 4th indexed element (starting from 0) of int (*tab)[6]. Fortunately this is OK as the calling code's array is large enough to handle index 4.

like image 85
chux - Reinstate Monica Avatar answered Nov 19 '25 08:11

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!