冲突指针的地址,并存储在指针

问题描述:

考虑这个C++程序中的地址之间的C++:冲突指针的地址,并存储在指针

#include<iostream> 
using namespace std; 

int main() { 
    int x = 7; 
    int *ip = &x; 
    cout << "the value of x is " << x <<endl; 
    cout << "the address of x is " << &x <<endl; 
    cout << "the address stored at ip is "<< ip <<endl; 
    return 0; 
} 

这是我得到的输出:

the value of x is 7 
the address of x is 0x28ff08 
the address stored at the pointer is 0x28ff08 

这对我来说很有意义。但是,如果我的代码更改为以下,我得到不同的输出:

#include<iostream> 
using namespace std; 

int main() { 
    int x = 7; 
    int *ip = &x; 
    cout << "the value of x is " << x <<endl; 
    cout << "the address of x is " << &x <<endl; 
    cout << "the address of the ip itself is "<< &ip <<endl; 
    return 0; 
} 

现在,我得到这样的输出:

the value of x is 7 
the address of x is 0x28ff0c 
the address of the ip itself is 0x28ff08 

在第一个代码,地址变量x和存储在指针ip处的地址是相同的,这对我很有意义。但在第二个程序中,ip本身的地址保持不变,但地址x似乎正在改变,这让我感到困惑。我期望变量x的地址与第一个程序中的地址和指针的地址保持不变。

有人可以解释这里发生了什么吗?

+6

a)你为什么期望这样做?b)你为什么会在意开始? –

+1

我真的不明白问题所在。你可以在问题中包含输出,而不仅仅是截图,也可以突出显示你期望的相同/不同的地址? – user463035818

+1

您是否期望第二个片段中'x'的地址与第一个片段中'x'的地址相同?如果是,为什么?当你运行相同的代码两次时,你甚至不能指望'x'被存储在同一个内存中 – user463035818

第一个代码中的值是相同的,因为ip的值是x的地址(同一件事,ip保留x的地址)。但在第二个代码中,结果是不同的,因为x的地址不是ip的地址(ip是不同的变量 - 能够保存其他变量的地址的指针)。计算机将决定创建它们 - 谁知道。我认为这只是巧合,其中一个变量是在相同地址上创建的,另一个是在不同的地址上创建的

我想你可能会在指针的值,指针的地址,指针的值和指针的地址之间混淆。我认为这可能是最好的解释通过一张照片。如果你写

int x = 7; 
int* ip = &x; 

然后,在内存中,事情是这个样子:

+-----------+     +-----------+ 
    |  7  | <------------ | Address A | 
    +-----------+     +-----------+ 
     int x      int* ip 
    Address A      Address B 

这里,变量x存储在某个位置(称之为A),并将其持有的价值7。变量ip存储在某个位置(称为B),并且其值为地址A。请注意,AB必须互不相同,因为xip占据单独的存储位置。

现在,想想当你写

cout << x << endl; 

这将打印出存储在x的价值,这是7会发生什么。 (我认为这不是很奇怪。)

如果你写

cout << &x << endl; 

要打印的是x坐在地址。无论A的价值如何,它都会随着程序运行到程序运行而变化。

如果你写

cout << ip << endl; 

要打印出存储在ip值。由于ip指向x,存储在ip中的值是x的地址,A恰好是。

但是,如果你写

cout << &ip << endl; 

要打印出ip变量的地址。该地址在上面用B表示,并且取决于程序的特定运行。请注意,AB而不是是同样的事情,所以你应该期望在这里看到不同的值。

要回顾一下:

+-----------+     +-----------+ 
    |  7  | <------------ | Address A | 
    +-----------+     +-----------+ 
     int x      int* ip 
    Address A      Address B 

     cout << x << endl; // Prints 7, the contents of x. 
     cout << &x << endl; // Prints A, the address of x. 
     cout << ip << endl; // Prints A, the contents of ip. 
     cout << &ip << endl; // Prints B, the address of ip. 

在你的情况,好像Ax地址,是0x28ff0cipB)地址是0x28ff08。这并不意味着x的地址发生了变化,而是表明ipx占用不同的内存地址。