"&的sizeof QUOT;知道数组的大小在C中的函数中不起作用 [英] "sizeof" to know the size of an array doesn't work in a function in C
问题描述
int main()
{
int laiArreglo [] = {5,8,2,3,1,4,6,9,2,10 },liElemento;
printf(\\\
Insert the number:);
scanf(%d,& liElemento);
ShowNumber(laiArreglo);
返回0;
}
void ShowNumber(int laiArreglo [])
{
int liContador;
printf(\\\
Numbers:);
(liContador = 0; liContador< sizeof(laiArreglo)/ sizeof(int); liContador ++)
{
printf(%d,laiArreglo [liContador]) ;
$ b我使用的是(sizeof(laiArreglo)/ sizeof( int))在main中,它的工作完美,但是,现在函数内部不起作用,为什么?
请记住,数组的名称decays指向其第一个元素。当您使用
sizeof(laiArreglo)
来自主要
,它的计算结果为
10 * sizeof(int)
而不是
sizeof(int *)
因为它是其中一种情况是衰变不会发生。
当您使用
ShowNumber(laiArreglo);
将其传递给函数,衰减确实发生。所以上面的语句相当于
pre $ Show $ Number(& laiArreglo [0]);
当您使用
sizeof(laiArreglo)
来自函数 ShowNumber
,它的计算结果为
sizeof(int *)
as laiArreglo
是指向 int $ c $的指针c>指向数组第一个元素的地址
laiArreglo
。
int main()
{
int laiArreglo[] = {5,8,2,3,1,4,6,9,2,10}, liElemento;
printf("\nInsert the number: ");
scanf("%d", &liElemento);
ShowNumber(laiArreglo);
return 0;
}
void ShowNumber(int laiArreglo[])
{
int liContador;
printf("\nNumbers: ");
for (liContador = 0; liContador < sizeof (laiArreglo) / sizeof (int); liContador++)
{
printf("%d ", laiArreglo[liContador]);
}
}
I was using (sizeof (laiArreglo) / sizeof (int)) in main and it worked perfectly but, now inside of a fuction it doesn't work, why?.
Keep in mind that the The name of an array "decays" to a pointer to its first element.When you use
sizeof(laiArreglo)
from main
,it evaluates to
10*sizeof(int)
and not
sizeof(int*)
as it is one of the cases where decay dosen't happen.
When you use
ShowNumber(laiArreglo);
to pass it to a function, the decay does occur. So the above statement is equivalent to
ShowNumber(&laiArreglo[0]);
and when you use
sizeof(laiArreglo)
from the function ShowNumber
, it evaluates to
sizeof(int*)
as laiArreglo
is a pointer to int
pointing to the address of the first element of the array laiArreglo
.
这篇关于"&的sizeof QUOT;知道数组的大小在C中的函数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!