我想获取数组的长度,例如int array[] = {1, 2, 3, 4}
。我使用 sizeof
来做到这一点。
int length(int array[])
{
return sizeof(array) / sizeof(int);
}
int main()
{
int array[] = {1, 2, 3, 4};
printf("%d\n", length(array)); // print 1
printf("%d\n", sizeof(array) / sizeof(int)); // print 4
}
那么,为什么函数 length
中的 sizeof(array)
返回 array
的指针大小呢?但在函数 main
中,它可以工作。
那么,我应该如何修改 length
函数来获取数组的长度?
最佳答案
一条特殊的 C 规则规定,对于函数参数,数组类型调整为指针类型。这意味着:
int length(int array[]);
相当于
int 长度(int *array);
因此,当您计算数组的size
时,您实际上是在计算指针的大小。
(C99, 6.7.5.3p7) "A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation."
关于c - 为什么 sizeof(param_array) 是指针的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38602460/