简体   繁体   English

C静态数组指针地址

[英]C static array pointer address

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? 我们为静态数组ad返回了相同的地址,为什么它们在输出上有所不同?

In main you're printing the address of the k pointer variable, not the address of the array that it points to. main您正在打印k指针变量的地址,而不是它指向的数组的地址。 If you do: 如果您这样做:

printf("main() => %p\n", k);

you'll get the same address as printed in aa . 您将获得与aa打印的地址相同的地址。

You wrote printf "&k" which should just be "k". 您编写了printf“&k”,它应该只是“ k”。 Hence you displayed the address of the variable k, and not of ad. 因此,您显示的是变量k的地址,而不是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;
}

&k returns the address of k and not the address it is pointing to. &k返回的地址k ,而不是它指向的地址。 So, what you are getting is the address of k . 因此,您得到的是k的地址。 You should change your printf() to 您应该将printf()更改为

printf("main() -> %p\n", k);
                        ^
                        No need for &

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM