Home > Blockchain >  Why &a shows different values in main() and other methods?
Why &a shows different values in main() and other methods?

Time:12-14

void f(int a[]);

int main() {
    int a[11];
    printf("1.%x  ", &a);
    f(a);
}

void f(int a[]) {
    printf("2.%x    ", &a);
}

Output:

1.e0de4940  2.e0de4928  

But the outputs will be the same when & are deleted. And why the difference is 12 no matter what the size of the array is?

CodePudding user response:

In main the call of printf

int a[11];
printf("1.%x  ",&a);

where you need to use the conversion specifier %p outputs the address of the array a.

Within the function f this call of printf outputs the address of the local variable (parameter) a of the function

printf("2.%x    ", &a);

As the array and the parameter a of the type int * occupy different extents of memory then their addresses are different.

Pay attention to that the parameter a gets the address of the first element of the array a declared in main. So the address stored in the parameter a is the same as the address of the array a in main. That is your could write

void f(int a[]);

int main() {
    int a[11];
    printf("1.%p  ", ( void * )&a);
    f(a);
}

void f(int a[]) {
    printf("2.%p    ", ( void * )a);
}

and as result you would get identical outputs.

You can simplify the code to make it easy to understand what is under the hood.

Consider the following code snippet

int a[11];
int *p = a;

as you see the two variables a and p occupy separate extents of memory. So these calls of printf yield different results

printf( "%p\n", &a );
printf( "%p\n", &p );

CodePudding user response:

When you write int a[], you refer to a pointer because arrays are pointers. To refer to where a points to, you simply write a. When you write &a, you are referring to the memory address of the pointer itself. The memory address of the pointer itself is different, because you are passing pointers (the memory adresses themselves) by value, meaning that they have a copy in each function.

CodePudding user response:

int a[] is syntactically the same as int* a both of them are pointers to integers (also known as int arrays). Hence the correct way is without &

void f(int a[]){
    printf("2.%x    ", a);
}
int main() {
    int a[11];
    printf("1.%x  ",a);
    f(a);
}

But the outputs will be the same when & are deleted. And why the difference is 12 no matter what the size of the array is?

Initially, you have & which first prints the address of int a[11]. Then the address of that array is passed to f() where it makes a different pointer that also points to the same address. However, those are two different pointers, hence when you print the addresses of the actual pointers they are obviously different no matter where they point.

The reason the difference of 12 is arbitrary, it just shows that those two pointers are 12 bytes away from each other

  • Related