Friday, January 25, 2013

What is the sizeof array type when passed as a function argument?

Sizeof() operator is used to find out the no. of memory bytes occupied by any datatype i.e. it will calculate the size of the given datatype. So if we pass a variable called i of type int, it will give output as 4 bytes, or if we pass a array type say arr which contains declaration as int arr[10] , it will give 40 as output.

We generally use sizeof() operator on array type to find out the number of elements an array contain by dividing the sizeof array by oth element of array (or any element).. The following program will illustrate this

#include<stdio.h>
int main()
{
    int arr[10],s;
    s=sizeof(arr)/sizeof(arr[0]);
    printf("sizeof arr %d\n",sizeof(arr));
    printf("no. of elements of arr %d\n",s);
    return 0;
}

Here the problem is what is the size of the array type in function when we pass it as a argument. This is something different because when we pass array as an argument, the array type decays to pointer. So we can't calculate the no.of elements in the function. This is described by the following program.