c++ - 变量引用以及指针如何与内存交互
问题描述
创建变量时,例如:
int x = 5;
它将存储在内存中的某个地方,很酷。
但是,当我通过执行以下操作更改变量的值时:
x = 10;
记忆中发生了什么?
新值是否会x
使用相同的内存地址覆盖旧值?
还是将新值存储在新的内存地址中,然后删除旧地址?
当我遇到指针时出现了这个问题。似乎使用指针更改变量的值与使用另一个值定义变量相同。
这是我的代码(大部分是评论(大声笑)):
#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
如您所见,内存地址是相同的,因此指针的意义是什么(双关语)。
解决方案
当您声明时,int x = 5;
您说的是x
具有自动存储持续时间并使用 value 进行初始化5
。
对于 的生命周期x
,指向x
(ie &x
) 的指针将具有相同的值。
您可以x
使用赋值或通过具有 setx = 10
的指针取消引用来更改 的值。*xPointer = 15
int* xPointer = &x;
语言标准没有提到指针值是内存地址,尽管它可能是。这是关于语言如何工作的常见误解。
(实际上,一个新的值x
可能会导致内存中的位置发生变化。只要指针值不变,语言就允许这样做。操作系统很可能会做类似的事情,以避免内存碎片整理。 )
推荐阅读
- python - 提取和替换 python-pptx 图形框架的文本
- javascript - 使用外部 javascript 创建在新选项卡/窗口中打开的超链接
- javascript - 三个 JS 旋转组,与 View Cube/Orientation Cube 的相机方向相同
- scala - 使用 http4s 获取请求中的 403 禁止错误
- c++ - 删除地图中一个过去的结束元素和分段错误
- python - 在 Python 3.8 中使用 qPython 和 Pandas 在 q-lang 中查询
- swift - RxSwift 中多节表格视图的 ViewModel 输入和输出
- mysql - 动态创建 PostgreSQL 表
- java - 在 Vaadin Flow 14 Web 应用程序中重置小部件的默认值而不触发其值更改侦听器
- python - SQLite 错误:尝试写入只读数据库