Jul 172012
 C Tags:  Add comments

The function myfunc below is suppposed to print the size of array passed to it as parameter(arr). What do you think is the problem (if any)

    void myfunc(int arr[], int n)
        printf("Size of Array : %d", sizeof(arr));
    int main()
        int a[5] = {1, 2, 3, 4, 5};
        myfunc(a, 5);


The problem is that in C language, array parameters are passed as pointers. So the signature of function myfunc above is exactly same as

    void myfunc(int *arr, int n)

Since arr is a pointer (and not an array) pointing to the first element of the array a(on the activation record of main function).

the sizeof operator will return the amount to memory allocated to the pointer variable arr(and not the array it is pointing). Which is not same as memory allocated to an array of 10 integers. If we really want to print the size of array, then the code should be

    printf("Size of Array : %d", sizeof(int)*n);


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>