Jump to content
  • Advertisement
Sign in to follow this  
jmpeer

c - quick question

This topic is 2898 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

I replicated my problem.
For some reason, char f adds 4 bytes to the size of the struct instead of 1.
Why?



#include <stdio.h>

typedef struct user user;

struct user
{
char a [51];
char b;
int c;
float d;
float e;
//char f;
};

int main()
{
user user;
printf("Size in Bytes: %d\n", sizeof(struct user));
return 0;
}



Share this post


Link to post
Share on other sites
Advertisement
The compiler is adding padding to the structure, for alignment purposes.

Compilers add space inside structures to make them line up. Sometimes it is optional for optimization, other times it is mandatory. For example, on many systems a float must be on 32-byte boundaries. If you were to cast a value to a float and it wasn't on a boundary the application will crash.

In this case it is operating on a 4-byte boundary, since the PC is designed with a 4-byte word size.


Share this post


Link to post
Share on other sites
You could use:

#pragma pack(1)
typedef struct user user;

struct user
{
char a [51];
char b;
int c;
float d;
float e;
//char f;
};
#pragma pack()

This will remove the so called boundary.

Share this post


Link to post
Share on other sites
The compiler is not allowed to rearrange data members inside a struct, but the order you arrange them in can decrease the amount of memory used. The ints and floats need to be aligned, but VS2008 doesn't align chars. But the struct itself needs to be a multiple of 4 in size if there are *any* types in it requiring alignment. Even if all ints occupy a position in the struct which is a multiple of 4, if you have an array of structs, and the struct itself isn't a multiple of 4 in size, then the ints will not be aligned in memory.
In your example, the compiler is padding the struct to 68 bytes to keep it a multiple of 4. But moving the "char f" up with the other chars doesn't decrease the size because the struct is already fully packed. (char a[51] and b total 52 bytes which is a multiple of 4)

Quote:
Original post by Vortez
You could use:

#pragma pack(1)
typedef struct user user;

struct user
{
char a [51];
char b;
int c;
float d;
float e;
//char f;
};
#pragma pack()

This will remove the so called boundary.


You often won't get any benefit from doing this, as the extra instructions the compiler generates to handle the off-boundary accesses will take up more memory than you save.

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.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!