1

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok, but technically in low-end address of k isn't the address of ad? so they might be the same, or no?
Yes, it is. When you return the array as a value, it's automatically converted to the address of the first element, just like when you pass it as an argument to printf.
2

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;
}

Comments

1

&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 &

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.