我發現我的bug(幾個小時後),並在下面的程序中將其隔離。問題在於當使用指向結構的指針時,計算pst2變量的值的方式。當使用指向char的指針時,一切正常。爲什麼是這樣?
(使用GCC /克++版本:(Debian的4.4.5-8)4.4.5)
(對於那些誰知道:我訪問以規則的偏移包含數據的分組的一個文件緩衝器)C++指針算術奇怪
#include <iostream>
#include "testpa.h"
#pragma pack(push)
#pragma pack(1)
//---------------------------
struct st_one
{
int i;
char c;
};
//---------------------------
struct st_two
{
long l;
int i;
};
#pragma pack(pop)
//===========================
int main()
{
int n=1024, np1=sizeof(st_one); //, np2=sizeof(st_two);
st_one *pst1, *pst1a;
st_two *pst2, *pst2a;
char *pc1, *pc2, *pc1a, *pc2a, *pb;
pb = new char[n];
pst1 = (st_one*)(pb);
pst2 = (st_two*)(pst1 + np1); //using pst1
pc1 = (char*)(pb);
pc2 = (char*)(pc1 + np1); //using pc1
pst1a = (st_one*)(pb);
pst2a = (st_two*)(pb + np1); //using pb
pc1a = (char*)(pb);
pc2a = (char*)(pb + np1); //using pb
std::cout << "\npb = " << (long)pb;
std::cout << "\n-----";
std::cout << "\npst1 = " << (long)pst1 << "\tpst2 = " << (long)pst2;
std::cout << "\npc1 = " << (long)pc1 << "\tpc2 = " << (long)pc2;
std::cout << "\n-----";
std::cout << "\npst1a = " << (long)pst1a << "\tpst2a = " << (long)pst2a;
std::cout << "\npc1a = " << (long)pc1a << "\tpc2a = " << (long)pc2a;
std::cout << "\n-----\n";
return 0;
}
輸出:
pb = 19546128
pst1 = 19546128 pst2 = 19546153 <--- WRONG!
pc1 = 19546128 pc2 = 19546133
pst1a = 19546128 pst2a = 19546133
pc1a = 19546128 pc2a = 19546133
我不明白這是怎麼回事。你期待什麼行爲? –
這是困難的方式。 'pst1 [offset] .c'有什麼問題?讓編譯器完成這項工作,它將會執行指針運算,並且不會比你更容易出錯。 – msw