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.
void test(int* array);
void test(int array[]);
void test(int array[3]);
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:
void test(char str[10]) { }
test("test"); // Works.
test("let's try something longer"); // Still works.
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 an int (*)[3]
, not int **
.
Because you would not be able to call such a function properly. In almost all contexts an array decays to a pointer to the first element, and at any attempt to call the function an array would first be converted to a pointer and the call would be a mismatch. The only contexts where an array does not decay are the operators sizeof
, _Alignof
, _Alignas
and &
. These are easier to detect syntactically.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.