Why does a C-Array have a wrong sizeof() value whe

2018-12-31 12:08发布

This question already has an answer here:

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?

6条回答
路过你的时光
2楼-- · 2018-12-31 12:41

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.

查看更多
浅入江南
3楼-- · 2018-12-31 12:55

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.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 12:55

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

sizeof C++ reference

查看更多
妖精总统
5楼-- · 2018-12-31 12:56

Because in C, C++, and Objective-C, functions cannot actually have array parameters. They only can have parameters that look like array parameters, but they aren't. In your example,

void test(int arr[])

the compiler sees "there is a parameter that looks like an array of int", and it replaces that parameter with a "pointer to int". So the function that you wrote is absolutely, one hundred percent, identical to

void test (int* arr)

Therefore, inside the function sizeof (arr) will give you the size of a "pointer to int".

查看更多
旧时光的记忆
6楼-- · 2018-12-31 12:59

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.

查看更多
梦醉为红颜
7楼-- · 2018-12-31 13:01

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.

查看更多
登录 后发表回答