size of array in c

后端 未结 6 1319
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 20:59

a simple question that bugs me. Say I have an array defined in main like so int arr[5]. Now, if I\'m still inside main and I set int i = sizeof(arr)/sizeo

6条回答
  •  再見小時候
    2020-12-01 21:37

    as far as I know arr is a pointer inside main too!

    That's the mistake. In main, where you defined int arr[5], arr is an array, not a pointer. Its size is equal to the size of the array, so 5*sizeof(int). When you passed it as a function parameter, that parameter had type int*, so inside the function, you were taking the size of an int* rather than an int[5].

    Here the output is 1. Any ideas why?

    This time, arr really is a pointer, since you declared it int *arr. But either way, whether it's int *arr or int a[5], *arr and arr[0] mean exactly the same thing: the first element. So of course they have the same size, and sizeof(*arr) / sizeof(arr[0]) is 1.

提交回复
热议问题