Inconsistent sizeof behavior in C
arrays, c, sizeof
Solution
int test_array[] = { 1, 2, 3, 4 };
int array_size = sizeof(test_array);
printf("size of test_array : %d.\n", array_size);
Here the compiler considers `test_array` as an array (it knows about the real size of the array at compile time) that's why you get the true size of `test_array`.
int func_array_size = sizeof_func(test_array);
printf("size of test_array from function : %d.\n",
func_array_size);
However if you pass an array to a function the compiler sees it as a pointer to the first element of the array (at compile-time your function don't know about the size of the array because you can call your function with any array that you have previously declared) that's why you're getting the size of a pointer.
Problem
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. ```