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)
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])
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With