C中行为的大小不一致

dav*_*k01 4 c arrays sizeof

可能重复:
C中Sizeof的行为

有人可以解释为什么下面的C代码表现如下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我期望输出为:

size of test_array : 16.
size of test_array from function : 16.
sizes match.
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了:

size of test_array : 16.
size of test_array from function : 4.
sizes don't match.
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 11

当您将数组作为函数参数传递时,它会衰减到指向其第一个元素的指针.
sizeofin函数返回指针的大小而不是数组.
同时,sizeofmain()数组的返回大小.当然,两者都不一样.

如果您想知道函数中数组的大小,则必须将其作为函数的单独参数传递.

int sizeof_func(int data[], size_t arrSize);
                            ^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)