指针地址方面问题搞不明白请大侠看看
- C/C++ code
#include <iostream>using namespace std;struct S{ int i; int *p;};int main(int argc, char *argv[]){ S s; int *p=&s.i; p[0]=1; // s.i p[1]=8; // &s.i 的下一个位置 也就是s.p的开始位置 cout<< p[0] << " " << s.i <<endl; cout<< &p[0] << " " << &s.i <<endl; cout<< p[1] << " " << s.p << " " <<endl;//s.p的地址为什么是0x8 ?? cout<< &p[1] << " " << &s.p << " " << &s.p[1] <<endl; cout<<endl; s.p=p; cout<< p[0] << " " << s.i <<endl; cout<< &p[0] << " " << &s.i <<endl; cout<< p[1] << " " << s.p << s.p[1] <<endl; cout<< &p[1] << " " << &s.p << &s.p[1] <<endl; s.p[1]=2;//*(s.p+1)=2 *(&s.p[0]+1)=2 cout<< s.p <<" "<< p << " " << &s.p << endl; //s.p的地址为什么是0x2?? return 0;} [解决办法]
struct S{
int i;
int *p;
};
在32位机上,int型和int*型数据所占用的内存空间都是4字节
因此structS占用8字节内存,前4字节和后4字节分别是整型变量i和指针变量p
int *p=&s.i;
p[0]=1; // s.i
p[1]=8; // &s.i 的下一个位置 也就是s.p的开始位置
将一个structS对象的i地址赋给局部变量p
此时p[0]为s.i,没什么疑问
p[1]则为p[0]后面第5到8个字节(偏移量4由局部变量p的类型int*确定,如果是double*p,那么就是第9到16个字节了),因此此时p[1]的内容即为s.p的内容
[解决办法]
。。。。第一个s.p是8是因为你的p[1]所指向的位置就是s.p的位置
最后那个s.p的地址不等于2呀
[解决办法]
http://topic.csdn.net/u/20120816/15/5477ab51-2816-41d4-bb49-69e4a0e1cfe8.html9-69e4a0e1cfe8.html 可以看看这个