I understand why an array decays to a pointer when passed to a function without specifying its size, eg.:
void test(int array[]);
Why does it do so when passed with the size? eg.
void test(int array[3]);
I am having trouble with sizeof
under the latter function signature, which is frustrating as the array length is clearly known at compile time.
Best Answer
All these variants are the same. C just lets you use alternative spellings but even the last variant explicitly annotated with an array size decays to a pointer to the first element.
That is, even with the last implementation you could call the function with an array of any size:
There is no magic solution, the most readable way to handle the problem is to either make a
struct
with the array + the size or simply pass the size as an additional parameter to the function.LE: Please note that this conversion only applies to the first dimension of an array. When passed to a function, an
int[3][3]
gets converted to anint (*)[3]
, notint **
.