gpt4 book ai didi

是否可以在其定义中取自动存储期限的变量的地址?

转载 作者:太空狗 更新时间:2023-10-29 15:45:44 25 4
gpt4 key购买 nike

是否允许在其定义的右侧获取对象的地址,如下面的 foo() 所示:

typedef struct { char x[100]; } chars;

chars make(void *p) {
printf("p = %p\n", p);
chars c;
return c;
}

void foo(void) {
chars b = make(&b);
}

如果允许,对它的使用是否有任何限制,例如打印是否正常,我可以将它与另一个指针进行比较等吗?

在实践中,它似乎在我测试的编译器上编译,大部分时间都具有预期的行为(但 not always ),但这远不能保证。

最佳答案

要回答标题中的问题,请记住您的代码示例,是的。 C 标准在 §6.2.4 中说明了同样多的内容:

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime.

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.

所以是的,您可以从声明点获取变量的地址,因为对象此时具有地址并且在范围内。下面是一个浓缩示例:

void *p = &p;

它的作用很小,但非常有效。

关于你的第二个问题,你能用它做什么。我主要可以说在初始化完成之前我不会使用该地址访问对象,因为初始化器中表达式的求值顺序未指定( §6.7.9 )。你很容易发现你的脚被击中了。

这确实发生在定义各种需要自引用的表格数据结构时。例如:

typedef struct tab_row {
// Useful data
struct tab_row *p_next;
} row;

row table[3] = {
[1] = { /*Data 1*/, &table[0] },
[2] = { /*Data 2*/, &table[1] },
[0] = { /*Data 0*/, &table[2] },
};

关于是否可以在其定义中取自动存储期限的变量的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50663893/

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