为什么将 C-Array 传递给函数时 sizeof() 值错误? [英] Why does a C-Array have a wrong sizeof() value when it's passed to a function?
问题描述
完整示例:
#include <stdio.h>
void test(int arr[]) {
int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
printf("%d
", 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
", 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(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.
这篇关于为什么将 C-Array 传递给函数时 sizeof() 值错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!