可变引用以及指针如何与内存相互作用
Variable referencing and how pointers interact with memory
创建变量时,例如:
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("%dn",x); // print the value of x
printf("%pn",xPointer); // print the reference of x
x = 10; //changing value of x
printf("%dn",x); //print new value of x
printf("%pn",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("%dn",x); //print new value of x
printf("%pn",xPointer); //print reference of x to see if it changed
return 0;
}
这是输出:
5
00AFF9C0
10
00AFF9C0
15
00AFF9C0
您可以看到内存地址是相同的,因此指针的意义是什么(双关语(。
在声明int x = 5;
时,您说x
具有自动存储持续时间,并使用值5
进行初始化。
对于x
的寿命,x
的指针(即&x
(将具有相同的值。
您可以使用分配x = 10
的x
的值,也可以通过指针解除*xPointer = 15
设置int* xPointer = &x;
。
语言标准没有提及指针值是一个内存地址,尽管可能是。这是关于语言如何工作的普遍误解。
(确实,x
的新值可能会导致内存中的位置更改。只要指针值不变,该语言就可以更改。操作系统可能会做类似的事情为此,为了消除内存碎片的利益。(
相关文章:
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 迭代时从向量和内存中删除对象
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 为什么示例代码访问IUnknown中已删除的内存
- 如何在C++类内存结构中创建"spacer"?
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 类型总是使用其大小存储在内存中吗
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 可变引用以及指针如何与内存相互作用