繁体   English   中英

检索有关&& x的信息,这些信息保留&x的地址

[英]Retrieve info about the &&x which keep the address of &x

我想用以下代码探索指针的壮举:

#include <stdio.h>
int x = 3;
int main(void)
{
    printf("x's value is %d, x's address is %p", x, &x);
    //printf("x's address is stored in", &&x);
}

它正常工作并获得输出

$ ./a.out
x's value is 3, x's address is 0x10b1a6018

当我使用&x ,会为其预留一个存储空间以保留地址0x10b1a6018,因此将打印一个地址。

随后,我打算获取有关存储另一个地址的地址的信息。

#include <stdio.h>
int x = 3;
int main(void)
{
    printf("x's value is %d, x's address is %p", x, &x);
    printf("x's address is stored in", &&x);
}

但是它报告错误为:

$ cc first_c_program.c 
first_c_program.c:14:40: warning: data argument not used by format string [-Wformat-extra-args]
    printf("x's address is stored in", &&x);
           ~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
first_c_program.c:14:42: error: use of undeclared label 'x'
    printf("x's address is stored in", &&x);
                                         ^
1 warning and 1 error generated.

如何获取有关存储值x地址的内存地址信息。

&x是一个临时值。 它没有存储在内存中并且没有地址。

同样, &42无效,因为42没有存储在内存中(这也是一个临时值)。

您收到的有点奇怪的错误消息是因为gcc实现了一元&&运算符,该运算符可用于获取标签的地址。 这是C语言的非标准扩展。

要获得更好的错误消息,请使用& &x (带空格)或&(&x)

但是,您想要的根本不存在。

&x是非左值表达式。 它没有位置。 &需要一个左值作为其操作数(或函数)。

&&x在标准C语言中根本不是有效的构造。地址根本不必存储在任何位置 -在您的程序中,因为x是全局变量,所以它是编译/链接时常量!


相反,GCC使用一元&&x作为扩展来获取跳转的标签x地址,用于计算的goto 因为&&被解析为单个令牌,并且&&在标准C中不允许作为一元运算符,所以这本身不会破坏C的一致性。

即你可以写

    static void *array[] = { &&foo, &&bar, &&hack };

    int i = 1;
    goto *array[i]; // jump to label bar

    ...

foo: ...
bar: ...
baz: ...

要执行所需的操作,需要将&x存储在变量中:

int* y = &x;
printf("%p", &y);

暂无
暂无

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

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