首页 > 解决方案 > 变量引用以及指针如何与内存交互

问题描述

创建变量时,例如:

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

如您所见,内存地址是相同的,因此指针的意义是什么(双关语)。

标签: c++pointersmemory

解决方案


当您声明时,int x = 5;您说的是x具有自动存储持续时间并使用 value 进行初始化5

对于 的生命周期x,指向x(ie &x) 的指针将具有相同的值。

您可以x使用赋值或通过具有 setx = 10的指针取消引用来更改 的值。*xPointer = 15int* xPointer = &x;

语言标准没有提到指针值是内存地址,尽管它可能是。这是关于语言如何工作的常见误解。

(实际上,一个新的值x 可能会导致内存中的位置发生变化。只要指针值不变,语言就允许这样做。操作系统很可能会做类似的事情,以避免内存碎片整理。 )


推荐阅读