如何解决为什么变量的地址与指针返回的地址不同?
我正在使用这个操作函数来获取指针地址,但它返回任何其他内容。
#include<iostream>
using namespace std;
int *manipulate( int &b) {
int *a=&b;
cout<<&a<<" "<<&b<<" "; // why memory add of 'a' and 'b' different ?
return a; // is it returing pointer which stores address of 'b' ?
}
int main() {
int x=44;
cout<<&x<<" "; // gives memory address of x;
int *ptr=&x;
cout<<ptr<<" "; // gives mem address of x;
int &l=x;
cout<<&l<<" "; // gives memory add of x;
int *c=manipulate(x); //storing returned pointer
cout<<&c; // why address of 'c' different to that of returned pointer?
return 0;
}
解决方法
在操作函数中,您通过引用收到 &b
。
在这一行:
int *a=&b;
您已经定义了一个指针变量 a,其值为 b 地址
在这一行:
cout<<&a<<" "<<&b<<" ";
你已经打印了a(指针)的地址和b的地址
如果你想要它们一样,你可以:
cout<<a<<" "<<&b<<" ";
最后你返回了 a(指向 b 的指针)
但在你的主要
int *c=manipulate(x);
您已经创建了一个指针名称 c,其地址值为 x
如果你想打印 x 的地址,你可以:
cout<<c;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。