Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading