tags:

views:

114

answers:

5

Complete example:

#include <stdio.h>

void test(int arr[]) {
    int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
    printf("%d\n", arrSize); // 2 (wrong?!)
}

int main (int argc, const char * argv[]) {
    int point[3] = {50, 30, 12};

    int arrSize = (int)(sizeof(point) / sizeof(point[0]));
    printf("%d\n", arrSize); // 3 (correct :-) )

    test(point);

    return 0;
}

Before passing it to a function, sizeof gives me the correct value. Doing the exact same thing on the exact same array in the function gives weird results. There's one element missing. Why?

+2  A: 

Because, when it's passed, only the pointer to array is actually being passed.

Your question is also answered at The C Programming FAQ. Question 6.21.

Pablo Santa Cruz
A: 

Because sizeof() does NOT tell you the size of an array in C. It does something completely different.

sizeof C++ reference

PeterK
If you have had a close look at the example, you would see that I don't use sizeof to directly get the number of elements in the array... sizeof should tell me how much memory is reserved for the array ... and actually that should match to how many elements are in there, when the size of an element is known. or am I missing something?
dontWatchMyProfile
I stand corrected. But as stated above, be careful with pointers. They tell you their size, not the size of the type you are pointing to.
PeterK
+5  A: 

Because array is decayed to a pointer when passed as function argument, so sizeof gives you 4 and 8 for 32- and 64-bit platforms respectively.

Nikolai N Fetissov
+10  A: 

When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself.

If you need the function to know the size of the array, you should pass it as a separate parameter:

void test(int arr[], size_t elems) {
   /* ... */
}

int main(int argc, const char * argv[]) {
   int point[3] = {50, 30, 12};
   /* ... */
   test(point, sizeof(point)/sizeof(point[0]));
   /* ... */
}

Also note that, for a similar reason (taking the sizeof a pointer), the sizeof(point)/sizeof(point[0]) trick doesn't work for a dynamically allocated array, only an array allocated on the stack.

Nick Meyer
+3  A: 

Also, it's important to understand that sizeof is evaluated at compile time. Since that's the case, it doesn't make sense to expect different output in test() depending on what was passed in. The sizeof calculation was done when the function was compiled.

tomlogic