Jump to content
  • Advertisement
Sign in to follow this  
cannonicus

memory layout in structs

This topic is 4565 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello Im programming in c++. Consider this:

struct foo
{
int a;
int b;
};

foo bar;


is it safe to assume that &bar == &bar.a and &bar.b = &bar.a + sizeof(int) on all systems? (well, all pc-systems is good enough). //Emil

Share this post


Link to post
Share on other sites
Advertisement
Although I believe 'int' is alreayd aligned to the 4-byte boundary, you should declare...

#pragma pack(1)


... if you use other data types. Inaddition, I don't believe its so much system dependent as it is compiler dependent. It should work on all the PCs that you need it to work on, unless your targetting something exceptional.

Edit: You can always check btw... just do a sizeof(struct foo) and see what it returns. if != sizeof(int) * 2 then there is padding, and thus, the assumption is no longer valid.

Share this post


Link to post
Share on other sites
Quote:
Original post by cannonicus
is it safe to assume that

&bar == &bar.a


I think that condition is usually the case, but if you want to be on the safe side, always use the member name when you want to operate on the member. Let the compiler deal with optimizing the access, since it will know for certain.

Share this post


Link to post
Share on other sites
Quote:

&bar == &bar.a

pretty much.

Quote:

&bar.b = &bar.a + sizeof(int)


not quite.

eg:

struct foo
{
short a;
int b;
char c;
long d;
SomeObject e;
};

foo bar;




the addresses of all b's members can't be gaurenteed.
most of the time it will be what you describe, except all objects with a size not equal to the word size will be padded to the word size.

however, it is better to use the pointer-to-member syntax to get these addresses.

eg.


struct foo
{
int a;
int b;
};

void bar( foo f, foo *fp )
{
int foo::*a_addr = &foo::a;
int foo::*b_addr = &foo::b;

cout << &(f.a) << '\n';
cout << &(f.*a_addr) << '\n';

cout << &(f.b) << '\n';
cout << &(f.*b_addr) << '\n';

cout << &(fp->a) << '\n';
cout << &(fp->*a_addr) << '\n';

cout << &(fp->b) << '\n';
cout << &(fp->*b_addr) << '\n';
}



each of the pairs of addresses should be the same...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!