问题
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?.
回答1:
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
.
回答2:
In your function ShowNumber()
,what you past is a pointer rather than an array.
来源:https://stackoverflow.com/questions/29447314/sizeof-to-know-the-size-of-an-array-doesnt-work-in-a-function-in-c