繁体   English   中英

为什么为传递给函数的指针获取不同的内存地址?

[英]Why Do I Get Different Memory Addresses For Pointer Passed To Function?

基本上我的问题是,当我运行这两段代码时,我得到了不同的内存地址。 仅通过添加&运算符,第一段代码为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;
}

第二个代码块,这次使用&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;

}

甚至指针本身也占用内存并具有与之关联的地址。

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

出现这种现象的原因是指针是按值传递的。 换句话说,当您的函数收到像这样的指针类型的参数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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM