“sizeof” to know the size of an array doesn't work in a function in C [duplicate]

岁酱吖の 提交于 2019-12-31 05:43:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!