Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decay of multidimensional arrays as function parameters

I know that for example this:

void foo(int a[])// or a[x]

will be considered by the compiler like this:

void foo(int *a)

But I don't know, and I didn't found anywhere how are multidimensional arrays seen by the compiler

For example:

void foo(int a[3][4])

Will it be something like this?

void foo(int (*a)[4])

Or something like this?

void foo(int **a)
like image 601
Leon Trotsky Avatar asked Jul 23 '18 19:07

Leon Trotsky


3 Answers

When an array decays, it converts into a pointer to the first element. In the case of int a[3][4], a is an array of int[4], so a pointer to an element of int [3][4] has type int (*)[4].

So this:

void foo(int a[3][4])

Is the same as:

void foo(int (*a)[4])
like image 89
dbush Avatar answered Nov 09 '22 14:11

dbush


The compiler cannot index a multi dimensional array passed to function correctly without knowing every dimension except the outermost.

So for a 1D array no length is needed:

void foo(int a[]);

and

void foo(int a[3]);

are equal although misleading, because C pays no attention to the length of an array: that is for the programmer to get right.

For a 2D array the inner dimension does have to be correct, or the compiler won't know how to index it. So

void foo(int a[][3]);

is good, but

void foo(int a[][]);

can't be coded, and

void foo(int a[42][3]);

is good but unnecessary, and not restrictive, since all the compiler needs is the information about how to index, and not how much.

like image 6
Weather Vane Avatar answered Nov 09 '22 16:11

Weather Vane


Multidimensional arrays are often a source of problems, especially if you want to allow a dynamic size.

In the general case, I would suggest to use

void foo(int* a, int size1, int size2);

or

void foo(int* a, int numSizes, int* sizes);

Explicitly passing the size limits the very common segfaults you'd get because of the pointer decay and the lack of checking. Using array types is very brittle and not recommended in most cases.

You also might want to specify the indexing method, it's usually a[size1*i+j] but you might want something else.

like image 1
meneldal Avatar answered Nov 09 '22 16:11

meneldal