N
Nafai
Hi. Have a look at this program:
struct tmp {
short a;
int b;
short c;
};
int main()
{
ofstream f("tmp.bin",ios::binary);
tmp t; t.a=5; t.b=2000; t.c=2;
f.write((const char*)&t.a,sizeof(short));
f.write((const char*)&t.b,sizeof(int));
f.write((const char*)&t.c,sizeof(char));
f.close();
ifstream g("tmp.bin", ios::binary);
tmp s;
g.read((char*)&s,sizeof(tmp));
cout << s.a << " " << s.b << " " << s.c << " " << endl;
cout << &s.a << " " << &s.b << " " << &s.c << " " << endl;
g.close();
}
The output should be (supposing &s==0x22fd48):
5 2000 2
0x22fd48 0x22fd4a 0x22fd4e
But the actual output is:
5 131072 -2764
0x22fd48 0x22fd4c 0x22fd50
So the problem is that the parts of the struct are not continuous in
memory!!! I mean, s.b should start 2 bytes after &s but actually it starts
after 4 bytes. That's why the g.read(...) doesn't work.
I tried:
but: cout << *((int*)((char*) (&s)+sizeof(short)))
and it output 2000.
In conclusion: &s+sizeof(s.a) != &s.b
Is all this my mistake or am I right??? I'm looking forward to an
explanation.
Thanks!
struct tmp {
short a;
int b;
short c;
};
int main()
{
ofstream f("tmp.bin",ios::binary);
tmp t; t.a=5; t.b=2000; t.c=2;
f.write((const char*)&t.a,sizeof(short));
f.write((const char*)&t.b,sizeof(int));
f.write((const char*)&t.c,sizeof(char));
f.close();
ifstream g("tmp.bin", ios::binary);
tmp s;
g.read((char*)&s,sizeof(tmp));
cout << s.a << " " << s.b << " " << s.c << " " << endl;
cout << &s.a << " " << &s.b << " " << &s.c << " " << endl;
g.close();
}
The output should be (supposing &s==0x22fd48):
5 2000 2
0x22fd48 0x22fd4a 0x22fd4e
But the actual output is:
5 131072 -2764
0x22fd48 0x22fd4c 0x22fd50
So the problem is that the parts of the struct are not continuous in
memory!!! I mean, s.b should start 2 bytes after &s but actually it starts
after 4 bytes. That's why the g.read(...) doesn't work.
I tried:
but: cout << *((int*)((char*) (&s)+sizeof(short)))
and it output 2000.
In conclusion: &s+sizeof(s.a) != &s.b
Is all this my mistake or am I right??? I'm looking forward to an
explanation.
Thanks!