Reputation: 198
We have a code.
#include <stdio.h>
int* aa(int s){
static int ad[2] = {0};
ad[0] = s;
printf("aa() -> %p\n", &ad);
return ad;
}
int main(void) {
int *k = aa(3);
printf("main() -> %p\n", &k);
return 0;
}
Compile, run.. output
aa() -> 0x80497d0
main() -> 0xbfbe3e0c
or i misunderstood or this code have problems.
we are returning the same address for static array ad
why on output they differ?
Upvotes: 1
Views: 1530
Reputation: 7006
&k
returns the address of k
and not the address it is pointing to. So, what you are getting is the address of k
. You should change your printf()
to
printf("main() -> %p\n", k);
^
No need for &
Upvotes: 1
Reputation: 781300
In main
you're printing the address of the k
pointer variable, not the address of the array that it points to. If you do:
printf("main() => %p\n", k);
you'll get the same address as printed in aa
.
Upvotes: 4
Reputation: 1054
You wrote printf "&k" which should just be "k". Hence you displayed the address of the variable k, and not of ad. :
#include <stdio.h>
int* aa(int s){
static int ad[2] = {0};
ad[0] = s;
printf("aa() -> %p\n", &ad);
return ad;
}
int main(void) {
int *k = aa(3);
printf("main() -> %p\n", k);
return 0;
}
Upvotes: 2