注 : 这仅仅是我的测试结论:
#include <iostream> using namespace std;
int main(){ int * i = new int; int * i2 = new int; cout << i << endl; cout << i2 << endl; *i = i2 - i; cout << *i << endl; } [vicky@localhost chapt6]$ g++ pointExap2.cpp [vicky@localhost chapt6]$ ./a.out 0x8049b58 0x8049b68 4 理解:实际上b68 – b58 = 10.10是16进制的,转换为10进制就是16.而4表示的是4个4byte.也就是16. 综合上面2个例子,我的理解是linux中2个同类型的数据,在内存中的地址相隔2.5个数据类型的长度.至于为什么是2.5就是避免指针在增加后于同类型的另外个数据内存相同.(错误的推论,正确推论见下.)
证明上述推测: #include <iostream> using namespace std;
int main(){ double * i = new double(1.0); cout << sizeof(*i) << endl; cout << "-------" << endl; double * i2 = new double(2.5); cout << i << endl; cout << i2 << endl; *i = i2 - i; cout << *i << endl; i+=2; cout << i << endl; cout << *i << endl; } [vicky@localhost chapt6]$ g++ pointExap3.cpp [vicky@localhost chapt6]$ ./a.out 8 ------- 0x8049da8 0x8049db8 // 2个地址相距还是10. 2 // b8 – a8 = 10 .转换为10进制为16 double类型为8byte,故差为2. 0x8049db8 // 由于i+=2,刚好 = i2.故再打印为i2. 2.5
在上述程序中加入. cout << "------" << endl; *i = 99.99; cout << *i << endl; cout << i << endl; cout << *i2 << endl; cout << i2 << endl;
------ 99.99 0x8049ed0 99.99 0x8049ed0
#include <iostream> using namespace std;
class A{ public: A(){} private: int i; double d; };
int main(){ A a; cout << sizeof(a) << endl; // 12 = 4(int) + 8(double) A* p1 = new A; A* p2 = new A; cout << p1 << endl; cout << p2 << endl; return 0; } [vicky@localhost chapt6]$ g++ pointExap4.cpp [vicky@localhost chapt6]$ ./a.out 12 0x8049d70 0x8049d80 80 – 70 = 10
总结:linux中,2个同类型的堆数据,在内存中的地址相隔10.并非之前假设的在内存中的地址相隔2.5个数据类型的长度.所以,指针在进行运算后,可能会指向相邻的指针指向的内存!!! |
在window平台下测试:
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) { int * i = new int(10); int * i2 = new int(99); cout << i << endl; // 00399448 cout << i2 << endl; // 00399478 cout << i2 - i << endl; // 12(16进制) 18(10进制)
cout << "---------" << endl; i+=3; cout << i << endl; // 00399454 16进制中454 - 448 = C 10进制为. 12 = 3* 4 cout << *i << endl; // 524724 故,i+=18/4 才对. cout << i2 << endl; // 00399478 cout << *i2 << endl; // 99 return 0;
}
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) { double * i = new double(9.9); double * i2 = new double(99.99);
cout << sizeof(*i) << endl;
cout << i << endl; // 00399448 cout << i2 << endl; // 00399480 cout << i2 - i << endl; // 7(16进制) 18(10进制)
cout << "---------" << endl;
}
#include "stdafx.h"
using namespace std;
class A{ public: A(){} private: int i; double d; };
int _tmain(int argc, _TCHAR* argv[]) { A a; cout << sizeof(a) << endl; // 16 A* p1 = new A; A* p2 = new A; cout << p1 << endl; // 003994C0 cout << p2 << endl; // 00399500 500- 4c0 = 40(16进制) 64(10进制) cout << p2 - p1 << endl; // 4 return 0; }
总结:似乎linux下,所有相同数据类型之间的间隔都是10(16进制),而windows下却似乎没有这样!!且同一个类,在linux下的大小为12 在windows下却为16. windows下类/struct分配的空间比linux下的大4.
|
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。