为什么 C 数组在传递给函数时有错误的 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\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(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 数组在传递给函数时有错误的 sizeof() 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!