0
void fun(int arr[8])
{
   printf("\nArray size inside fun() is %d", sizeof(arr));
}

int main()
{
   int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};

   printf("Array size inside main() is %d", sizeof(arr));
   fun(arr);

   return 0;
}

Why the size of array arr[8] inside function fun() is 4 bytes and array arr[8] in function main() is 32 bytes? Although they can store 8 integers each of 4 bytes. The size of the array arr[8] in func() should have also been 32.

What actually happens when we pass an array as a parameter?

  • "What actually happens when we pass an array as a parameter?" A pointer to the first element of the array is passed. Also, although a parameter can be declared with an array type, it gets automatically adjusted to a pointer type. See C11 [6.7.6.3 paragraph 7](https://port70.net/~nsz/c/c11/n1570.html#6.7.6.3p7): – Ian Abbott Jun 17 '20 at 14:34

1 Answers1

0

In main, sizeof is calculating arr to be 8 * sizeof(int). In fun, sizeof is calculating arr to be sizeof(int *). As you can see, an array decays to a pointer when passed to a function.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
  • That means arr[] in fun should be treated as only a single pointer of an integer. But my question is how only a single pointer points and prints all data passing from the main function? For example in this code: void fun(int arr[],int n) { int i; for(i=0;i – user9817940 Jun 17 '20 at 14:44
  • @user9817940 Look at the duplicate question. Everything is explained best there. `arr` is not a array in `fun`, it is a pointer. With this pointer you access the values of the array in the caller. – RobertS supports Monica Cellio Jun 17 '20 at 14:45
  • When you increment the address of an `int` pointer (e.g. `arr++`) you move to the address of the next `int`. In this way, you can use a `int *` to access more than one element in an `int` array. – Fiddling Bits Jun 17 '20 at 15:05