user968000
user968000

Reputation: 1843

Array as an argument to a function

When an array is passed as an argument , the compiler generates a pointer to the array's first element and that pointer is passed to the function rather than the full array, so my question is why we can print the values of the array when we print array[i]?

void FunctionApi(int array[])
{
    int i;
    for(i=0;i<8;i++)
    {
         printf("Value =%d\n",array[i]);
         //I understand the reason behind the following two lines but not the above          line.
         //printf("noOfElementsInArray=%d\n",*array);
         //*array++;
    }

}

int main()
{
    int array[8]={2,8,10,1,0,1,5,3};
    int noOfElementsInArray;
    noOfElementsInArray=sizeof(array)/sizeof(int); 
    printf("noOfElementsInArray=%d\n",noOfElementsInArray);
    FunctionApi(array);
    return 0;   

}

Upvotes: 1

Views: 99

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Array's elements are stored together in consecutive locations. That is why knowing the address of the initial element is sufficient to know where the rest of the elements are.

The only trick is knowing how many elements the array has. This is not passed along with the array, so you need to pass it separately. It is not a concern for your program because you hard-coded it to eight, but in general if you pass an array as an argument, you also need to pass its size as a separate parameter:

void FunctionApi(int array[], size_t count) {
    int i;
    for(i=0;i<count;i++) {
        printf("Value =%d\n",array[i]);
    }
}

As far as the noOfElementsInArray=sizeof(array)/sizeof(int); calculation goes, this trick works only in the caller, where array is an array, not a pointer to the initial element of the array. At this location the compiler knows that the size of the array is eight times the size of an int, so dividing out the sizeof(int) gives you the number of elements in the array.

Upvotes: 2

Ganesh
Ganesh

Reputation: 5980

When you pass the name of an array, this is pointer to the first element as well as the entire array. Hence, when you access different elements as array[i] you are accessing successive data equivalent to *(array + i).

Upvotes: 0

Jesus Ramos
Jesus Ramos

Reputation: 23268

Because array[i] is syntactically equivalent to *(array + i)

Upvotes: 1

Related Questions