gpt4 book ai didi

c - 为什么我不能在 C 中使用 `&&a`?

转载 作者:太空宇宙 更新时间:2023-11-04 05:02:06 24 4
gpt4 key购买 nike

int main(int argc, char * argv[]) {
int a = 10;
int * sp = &a;
int * * dp1 = &sp;
int * * dp2 = &&a; // NG
int * * dp3 = &(&a); // NG
int * * dp4 = &((int *) &a); // NG
}
$ cc test.c
test.c: In function ‘main’:
test.c:6:17: error: lvalue required as unary ‘&’ operand
int * * dp3 = &(&a); // NG
^
test.c:7:17: error: lvalue required as unary ‘&’ operand
int * * dp4 = &((int *) &a); // NG
^
test.c:5:3: error: label ‘a’ used but not defined
int * * dp2 = &&a; // NG
^

最佳答案

Why can't I use &&a

因为 & 为您提供了变量的地址,而 &a 不是变量。

C 11 草案规定了以下内容:

6.5.3.2 Address and indirection operators

Constraints

1 The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

[...]

Semantics

3 The unary & operator yields the address of its operand. [...]

要绕过这个“限制”,可以使用这样的复合文字(至少假设是 C99)来引入临时存储:

int a = 42; 
int ** ppa = &((int *){&a});

作为引用以下错误消息的旁注:

test.c:5:3: error: label ‘a’ used but not defined
int * * dp2 = &&a; // NG
^

gcc(可能还有其他)定义了 C 标准的扩展,如果操作符标识标签,则允许在单个操作符上使用 && 运算符。 (更多相关信息:https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html)

例子:

void * pv = &&lbl;

goto *pv;

/* some dead code */

lbl:;

/* living code again here */

关于c - 为什么我不能在 C 中使用 `&&a`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30912008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com