为什么当它传递给函数的C-阵列有一个错误的sizeof()值? [英] Why does a C-Array have a wrong sizeof() value when it's passed to a function?

查看:91
本文介绍了为什么当它传递给函数的C-阵列有一个错误的sizeof()值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完整的例子:

#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;
}

将它传递给一个函数之前,sizeof的给了我正确的值。这样做的功能完全相同的阵列上的完全一样的东西给了奇怪的结果。还有一个因素缺失。为什么呢?

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?

推荐答案

当你传递一个数组C中的函数,数组衰变成一个指针,它的第一个元素。当您使用的sizeof 的参数,你正在服用的指针,而不是数组本身的大小。

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]));
   /* ... */
}

另外要注意的是,对于类似的原因(取的sizeof 指针),在的sizeof(点)/ sizeof的(点[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.

这篇关于为什么当它传递给函数的C-阵列有一个错误的sizeof()值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆