创建变量时,例如:
int x = 5;它会存储在内存中的某个地方,很酷。
但是,当我通过执行以下操作更改变量的值时:
x = 10;内存中发生了什么?
x的新值是否会覆盖使用相同内存地址的旧值?
或者新值被存储在新的内存地址中,然后旧地址被删除?
当我遇到指针时,这个问题就出现了。似乎使用指针更改变量的值与使用另一个值定义变量是相同的。
这是我的代码(大部分是注释(lol)):
#include "iostream"
int main()
{
int x = 5; // declaring and defining x to be 5
int *xPointer = &x; // declare and define xPointer as a pointer to store the reference of x
printf("%d\n",x); // print the value of x
printf("%p\n",xPointer); // print the reference of x
x = 10; //changing value of x
printf("%d\n",x); //print new value of x
printf("%p\n",xPointer); //print the reference of x to see if it changed when the value of x changed
*xPointer = 15; //changing the value of x using a pointer
printf("%d\n",x); //print new value of x
printf("%p\n",xPointer); //print reference of x to see if it changed
return 0;
}这是输出:
5
00AFF9C0
10
00AFF9C0
15
00AFF9C0正如你所看到的,内存地址是相同的,因此指针的意义是什么(双关语)。
发布于 2019-07-05 21:20:01
当您声明int x = 5;时,您表示x具有自动存储持续时间,并且是用值5初始化的。
对于x的生存期,指向x的指针(即&x)将具有相同的值。
您可以使用赋值x = 10或通过设置了int* xPointer = &x;的指针取消引用*xPointer = 15来更改x的值。
语言标准没有提到指针值是内存地址,尽管它可能是。这是一种关于语言如何工作的常见误解。
(实际上,x的新值可能会导致内存中的位置发生变化。这是语言所允许的,只要指针值不变。为了避免内存碎片整理,操作系统很可能会做类似的事情。)
https://stackoverflow.com/questions/56903831
复制相似问题