vipulnj
vipulnj

Reputation: 135

Array not getting passed properly

The array that I try to send to the called function is not being sent properly. Suppose I have inserted five elements in the array 'a' and i pass the array using the function insert function and check the size of array in using the last two lines of the following code, it displaying one less than the actual size of the array. Why is this happening??

void main()
{
    //rest of the code     
    insert(a,key);   //user-defined function
}

void insert(int a[],int key)
{
    int *p=a;
    int n = sizeof(a);
    printf("No. of elements entered:%d\n",n);
}

Upvotes: 2

Views: 74

Answers (1)

Paul R
Paul R

Reputation: 212949

sizeof(a) is just giving you the size of a pointer in bytes (4 on your machine, apparently). There is no way to determine the size of an array once it has been passed to a function, since arrays decay to pointers when passed as function parameters. You should instead pass the size of the array as a separate parameter, e.g.

void insert(int a[], int n, int key)
{
    printf("No. of elements entered: %d\n", n);
}

int main()
{
    int a[5];

    insert(a, 5, key);
}

Upvotes: 5

Related Questions