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

标签 c pointers declaration

执行第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/

相关文章:

c - 在不使用 '-' 运算符的情况下减去两个数字

c - 赋值从整数生成指针而不进行强制转换

c++ - C++候选函数不可行: no known conversion from 'int' to 'int *' for 1st argument; take the address of the argument with &

使用 DLL 的循环队列,全局声明的指针未正确初始化

c++ - using 声明是否能够引用友元函数

c - 如何从 Void 函数返回值?

c - 即使定义了 %.o,也没有制作 something.o 的规则

matlab - 使用 MATLAB 从另一个应用程序中的控件获取文本

c++ - 我可以依靠我的编译器来诊断 TU 中的类型不匹配吗?

java - 哪些情况下允许在静态初始化程序 block 中进行前向引用?