0
#include <stdio.h>
 

void fun(int arr[]) 
   unsigned int n = sizeof(arr)/sizeof(arr[0]);
   printf("\nArray size inside fun() is %d", n);
}
int main()
{
   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
   unsigned int n = sizeof(arr)/sizeof(arr[0]);
   printf("Array size inside main() is %d", n);
   fun(arr);
   return 0;
}

Why are people writing that n=size of array/ size of arr[0] ? and also why the values of n different ? inside main and inside function?

Heatblast
  • 55
  • 6
  • Inside main `arr` is an array; inside the function `arr` is a pointer. You may like section 6 of the [comp.lang.c faq](http://c-faq.com/). – pmg Jun 10 '21 at 07:13

1 Answers1

2
int n = sizeof(arr)/sizeof(arr[0]);

This line is used to calculate the number of items in the array. sizeof(arr) gives the total size consumed by the array, and sizeof(arr[0]) gives the size allocated to each element. For example, if it is int so GCC compiler allocation it 4 bytes.

In C, When you pass an array to a function as an argument, C doesn't pass a copy of the whole array, rather it passes the pointer to the first element of the array. So,

fun(arr); // it passes the base address of the array, &arr[0]

So we cannot determine the length of the array inside the called function. If you run sizeof(arr) inside function fun then it gives the size of the pointer. (which is usually 4 or 8 depending on your platform).

Thus, the right way to pass an array to a function is to pass also the size of the array as a second argument:

fun(arr, n); //arr is array and n is the length of the array

Hope, you understand the concept.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
iabhitech
  • 66
  • 5