don*_*ile 33 c arrays function 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;
}
Run Code Online (Sandbox Code Playgroud)
在将它传递给函数之前,sizeof给出了正确的值.在函数中完全相同的数组上执行完全相同的操作会产生奇怪的结果.缺少一个元素.为什么?
Nic*_*yer 44
将数组传递给C中的函数时,数组会衰减为指向其第一个元素的指针.在sizeof
参数上使用时,您将获取指针的大小,而不是数组本身.
如果您需要函数来了解数组的大小,则应将其作为单独的参数传递:
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]));
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
还要注意,由于类似的原因(采用sizeof
指针),该sizeof(point)/sizeof(point[0])
技巧不适用于动态分配的数组,只能在堆栈上分配一个数组.