Splitting a linked list
July 11, 2012
Find kth element in union of two arrays
July 21, 2012

Error in C language code

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);
    }

Solution:
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

Your email address will not be published. Required fields are marked *