可变引用以及指针如何与内存相互作用

Variable referencing and how pointers interact with memory

本文关键字:内存 相互作用 指针 引用      更新时间:2023-10-16

创建变量时,例如:

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 = 10x的值,也可以通过指针解除*xPointer = 15设置int* xPointer = &x;

语言标准没有提及指针值是一个内存地址,尽管可能是。这是关于语言如何工作的普遍误解。

(确实,x 的新值可能会导致内存中的位置更改。只要指针值不变,该语言就可以更改。操作系统可能会做类似的事情为此,为了消除内存碎片的利益。(