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.

#include<stdio.h>
void fun(int arr[])
{
    int s,i;
    s= sizeof(arr)/sizeof(arr[0]);
    printf("fun: sizeof arr %d\n",sizeof(arr));
    printf("fun: no.of elements %d\n",s);
    for(i=0;i<s;i++)
        printf("arr[%d] %d\n ",i,arr[i]);
}
int main()
{
    int arr[10]={1,2,3,4,5,6,7,8,9,10},s;
    s= sizeof(arr)/sizeof(arr[0]);
    printf("main: sizeof arr %d\n",sizeof(arr));
    printf("main: no.of elements %d\n",s);
    fun(arr);
    return 0;
}
Output:
main: sizeof arr 40
main: no.of elements 10
fun: sizeof arr 4
fun: no.of elements 1
arr[0] 1
-->
As the array type decays into pointer, so its size will be size of int (4 bytes). So 4/4 which gives 1 as the no.of elements. 

To get the no.of elements of array, we need to pass it as an another argument to the function as below.

             void fun(int arr[],int size);
If you like this article

No comments:

Post a Comment