为什么我会为指针传递功能获得不同的内存地址?

时间:2016-10-19 17:24:18

标签: c++ memory

基本上我的问题是,当我运行这两段代码时,我得到不同的内存地址。第一段代码为rValue提供了一定的内存地址,第二段为rValue提供了不同的内存地址,只需添加一个&运营商。为什么会这样?

#include <iostream>
using namespace std;


int pMem(int *rValue){

cout << "Value of rValue is " << *rValue << endl;;
cout << "Address of rValue is " << rValue << endl;
*rValue = 15;
cout << "Value of rValue now is " << *rValue << endl;
cout << "Address of rValue is " << rValue << endl;

return *rValue;

}

int main() {


int value = 8;
int *pValue = &value;

pMem(&value);



cout << "Value = " << value << endl;
cout << "Address of Value: " << pValue << endl;
cout << "Value at memory address " << pValue << ": " << *pValue << endl;


return 0;
}

第二段代码,这次使用&amp; rValue ...我获得的内存地址与第一段代码不同。

#include <iostream>
using namespace std;


int pMem(int *rValue){

cout << "Value of rValue is " << *rValue << endl;;
cout << "Address of rValue is " << &rValue << endl;
*rValue = 15;
cout << "Value of rValue now is " << *rValue << endl;
cout << "Address of rValue is " << &rValue << endl;

return *rValue;

}

int main() {


int value = 8;
int *pValue = &value;

pMem(&value);



cout << "Value = " << value << endl;
cout << "Address of Value: " << pValue << endl;
cout << "Value at memory address " << pValue << ": " << *pValue << endl;


return 0;

}

2 个答案:

答案 0 :(得分:3)

即使指针本身占用内存并且有一个与之关联的地址。

因此&amp; rValue是指针rValue的地址,除非它是指向函数的指针,否则该地址将不同。

答案 1 :(得分:2)

此行为的原因是指针按值传递。换句话说,当你的函数接收到像这样的指针类型参数rValue

int pMem(int *rValue)

C ++为类型为int*的全新变量分配空间,并在内存中使用自己的地址。此变量从您传递给pMem的指针表达式初始化。除此之外,它是一个单独的变量,其行为类似于pMem的局部变量。特别是,参数本身的任何重新分配都不会对调用者产生影响。

执行此操作时,将打印该参数变量的地址:

cout << &pValue << endl; // Prints a new address

如果您想查看传递给函数的地址,请打印指针,而不是地址:

cout << pValue << endl;  // Prints the address that you passed
相关问题