怎样的sizeof()引用论据通工程 [英] how sizeof() works in pass by reference arguments
问题描述
我通过一个阵列的功能,并试图找到数组的长度。但是没有预料到的结果。任何人可以解释一下吗?
INT的main()
{
int数组[10] = {0};
FUNC(数组);
返回0;
}
无效FUNC(INT ARR [])
{
的printf(数组长度为%d,(的sizeof(ARR)/ sizeof的(ARR [0]));
}
它给出了答案2。
当我试图main函数里面同样的操作,它工作正常(答案是10)。
//在Linux中使用gcc编译
在我看来,其结果是造成的,因为的sizeof(ARR)== 8
(的大小指针在电脑上)和的sizeof(ARR [0])== 4
,因为它是一个整数,因此 8/4 == 2
。
这声明:无效FUNC(INT ARR [])
告诉函数期望的的指针为int 的作为参数
这是我不清楚是否可能参照计算的sizeof
的数组。 C
函数接受数组引用作为参数总是倾向于接受它们的长度也作为参数。</ P>
与的main()
功能不同的是,里面的主
阵列
变量的类型的 INT [10]
,从而的sizeof
是能够得到以字节为单位的长度。在 FUNC
,改编
的类型为为int *
那么的sizeof
为您提供了一个指针字节只有长度。
I passed a array to function and tried to find the length of the array . but the result was not expected . can anybody explain please?
int main()
{
int array[10]={0};
func(array);
return 0;
}
void func(int arr[])
{
printf("length of an array is %d ",(sizeof(arr)/sizeof(arr[0]));
}
it gives the answer 2. when I tried the same operation inside main function it works fine (answer is 10). //using gcc complier in linux
Seems to me that the result is caused because sizeof(arr) == 8
(size of a pointer on your PC) and sizeof(arr[0]) == 4
because it is an integer hence 8/4==2
.
This declaration: void func(int arr[])
tells the function to expect a pointer to int as argument.
It is not clear to me whether is possible to calculate the sizeof
an array by reference. C
functions accepting array reference as arguments always tend to receive their length too as argument.
The difference with main()
function is that inside main
array
variable is of type int[10]
, thus sizeof
is able to get its length in bytes. In func
, arr
is of type int*
so sizeof
gives you only the length in bytes of a pointer.
这篇关于怎样的sizeof()引用论据通工程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!