指针如何偏移的

hjk_thinking 2008-11-16 03:34:58

#include <iostream>
using namespace std;

char a='b';
string b="Microsoft";

class test
{
public:
test(){vpt=&a;vpt2=&b;}
char* vpt;
string* vpt2;
};

void main()
{
test t;
cout<< hex <<(int*)(&t)<<endl;//t的地址

cout<< hex << *(int*)(&t)<<endl; //如何找到t里面的b的地址的?


}







希望能给出具体点的说明,或者是参考文献,最好能举例说明一下!!
//先谢谢了
...全文
255 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
机智的呆呆 2008-11-16
  • 打赏
  • 举报
回复
从&t地址开始,就是t对象对应内存里的数据,其中&t~&t+3是指针变量vpt的存储空间 &t+4~&t+8是指针变量vpt2存储空间,&t开始移动4个字节内存单位也就是一个指针类型的存储的空间((int*)(&t)+1)所得到的内存地址值是vpt2的起始内存地址值,也就是&t+4,&t+4~&t+8中存储的就是&b,所以*(int*)((int*)(&t)+1)就取出了,取4个内存单位就行。
机智的呆呆 2008-11-16
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

char a='b';
string b="Microsoft";

class test
{
public:
test(){vpt=&a;vpt2=&b;}
char* vpt;
string* vpt2;
};

void main()
{
test t;
cout<< hex <<(int*)(&t)<<endl;//t的地址

cout<< hex << *(int*)((int*)(&t)+1)<<endl; //如何找到t里面的b的地址的?
cout<<hex<<&b<<endl;
system("pause");


}
rollrock1987 2008-11-16
  • 打赏
  • 举报
回复
对类的操作还不行啊 多看看书
帅得不敢出门 2008-11-16
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

char a='b';
string b="Microsoft";

class test
{
public:
test(){vpt=&a;vpt2=&b;}
char* vpt;
string* vpt2;
};

int main()
{
printf("%p %p\n",&a,&b);
test t;
cout<< hex <<(int*)(&t)<<endl;//t的地址

cout<< hex << *(int*)(&t)<<endl; //如何找到t里面的b的地址的?
printf("%p %p",t.vpt,t.vpt2);
return 0;
}


toadzw 2008-11-16
  • 打赏
  • 举报
回复
这二个都是全局的变量,当然从全局中以访问到啊,你将类中的指针直接指向了他们,没有偏移量的计算;
toadzw 2008-11-16
  • 打赏
  • 举报
回复
这二个都是全局的变量,当然从全局中以访问到啊,你将类中的指针直接指向了他们,没有偏移量的计算;

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧