Is this:
void test(int arr[]) {
printf("%d\r\n", sizeof(arr));
}
valid?
It is NOT a valid1 code, however it is equivalent to: sizeof(int*)
, not size of the array, arr
, because as you pass the array as an argument it decays to a pointer2 i.e. it looses the information about the size of the whole array. The only way to convey this information into a function is through an additional, second, parameter.
Is there a way to make test()
output different values by using sizeof
on function argument handed in like on array?
If you want to print the size of the array you are passing, you could use something like: sizeof(array)
as an second argument of the function, where the function signature would be:
void test(int arr[], size_t size);
you could insert the above as second argument and get the size of the first argument.
1. There is a type mismatch between size_t
(the returning type of sizeof()
) and int
(the expected type matching the specifier "%d"
in the printf(),
, which leads to undefined behaviour.
2. arr[]
outside the function represents the whole array as an object and that is why if you apply sizeof()
you will get the size of the whole array, however, when passed as argument, arr
decays to a pointer of the array's first element and if you apply sizeof()
you'll get the size of the type of the pointer.