Possible Duplicate:
Behaviour of Sizeof in C
Can somebody explain why the following piece of C code behaves as it does:
#include <stdio.h>
int sizeof_func(int data[]) {
return sizeof(data);
}
int main(int argc, char *argv[]) {
int test_array[] = { 1, 2, 3, 4 };
int array_size = sizeof(test_array);
printf("size of test_array : %d.\n", array_size);
int func_array_size = sizeof_func(test_array);
printf("size of test_array from function : %d.\n",
func_array_size);
if (array_size == func_array_size) {
printf("sizes match.\n");
} else {
printf("sizes don't match.\n");
}
return 0;
}
I expected the output to be:
size of test_array : 16.
size of test_array from function : 16.
sizes match.
But instead I got:
size of test_array : 16.
size of test_array from function : 4.
sizes don't match.
When you pass an array as function argument it decays in to a pointer to its first element.sizeof
in function returns size of the pointer not the array.
While, sizeof
in the main()
returns size of the array. Naturally, both are not the same.
If you want to know the size of the array in the function you will have to pass it as an separate argument to the function.
int sizeof_func(int data[], size_t arrSize);
^^^^^^^^^^^^
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