how sizeof() works in pass by reference arguments

后端 未结 6 1767
深忆病人
深忆病人 2021-01-22 04:56

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 arra         


        
6条回答
  •  死守一世寂寞
    2021-01-22 05:41

    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.

提交回复
热议问题