diffrent results when trying to find length of an array using pointer arithmetic inside a function and inside of main

Advertisements

for some odd reason when I run this code:

int func(int arr[],int n) {
    int a = *(&arr + 1) - arr;
    printf("%d",a);
}

I get an address,

and when I run the same code inside main I get the length of the array.

any idea why?

I ran it inside main and it gave me the length of an array, and when I ran it inside a function it gave me an address.

>Solution :

This function declaration

int func(int arr[],int n){

is adjusted by the compiler to

int func(int *arr,int n){

On the other hand. the array passed to the function as an argument expression is implicitly converted to a pointer to its first element of the type int *.

So within the function you actually deal with a pointer instead of an array.

Leave a Reply Cancel reply