gpt4 book ai didi

c - 新声明后内存地址是否改变?

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:42 25 4
gpt4 key购买 nike

执行第0句后,n1、n2、*pn的内存地址分别为ADDR:0061FF2C、0061FF28、0061FF24。执行完1), 2), 3)后会不会改变?我把 printf 用于每个代码,但它们似乎没有改变。从理论上讲,它们不应该因为变量被分配了新值而改变吗?

#include <stdio.h> 
int main(void)
{
int n1=3, * pn = &n1;
int n2=0;

printf("%p, %p, %p\n", &n1, &n2, &pn); // 0)
n2 = *pn; // 1)
*pn = n2 + 1; // 2)
n1 = *pn + *(&n2); // 3)
printf("%d, %d, %d\n",n1,n2,*pn); // 4)
return 0;
}

最佳答案

让我们看看标准对此有何评论 -

引用 C11,章节 §6.2.4p2

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,[33] and retains its last-stored value throughout its lifetime. [...]

引用 C11,章节 §note33

The term "constant address" means that two pointers to the object constructed at possibly different times will compare equal. The address may be different during two different executions of the same program.

现在我们拥有的对象是n1n2pn。所有这三个都有自动存储持续时间。

因此构造了指向这些的任意两个指针(在第一个 printf 中使用 &,如 &n1&n2)在不同的时间也会比较相等。即使它们的值在执行过程中发生变化,也是如此。

关于c - 新声明后内存地址是否改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47193851/

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