开发者

Why is sizeof giving me this result?

I have this code

struct Student {
char name[48];
float grade;
int marks[10,5];
char gender;
};

Student s;

Now I have to get the sizeof s

so I added

printf("%d",sizeof(s));

now when I hit compile the result showing is 256

and its wrong becau开发者_高级运维se it shoud be 253

as because the size of

char name[48]; ----> 48

and

float grade; -----> 4

and

int marks[10,5]; ------> 200

and

char gender; ------->1

so 48+4+200+1 = 253

so why is it telling me 256?

================================

this part is written after I saw your answers

I learned that

Suppose I have this structure: struct { char a[3]; short int b; long int c; char d[3]; };

So ..

+-------+-------+-------+

|           a           |

+-------+-------+-------+

|       b       |

+-------+-------+-------+-------+

|               c               |

+-------+-------+-------+-------+

|           d           |

+-------+-------+-------+

In the packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers willpad'' the structure (as if with extra, invisible fields) like this:

+-------+-------+-------+-------+

|           a           | pad1  |

+-------+-------+-------+-------+

|       b       |     pad2      |

+-------+-------+-------+-------+

|               c               |

+-------+-------+-------+-------+

|           d           | pad3  |

+-------+-------+-------+-------+

so if Im having the maximum size is 200 should the padding be like

48 + 152

4 + 196

200 + 0

1 + 199

to make them in a perfect shape


There may be padding bytes between the members of the struct or at the end of the struct.

In this case, it is likely that there are three bytes of padding at the end of the struct, after the single char member, to ensure that the size of the struct is a multiple of four.


The compiler pads the struct to align to a word boundary. It's easier for the processor to handle chunks of 256 bytes than an odd number like 253.


int marks[10,5];

should be

int marks[10][5];

There may also be issues of padding and alignment to consider.


If using Visual C++, add #pragma pack(1) to the top of your source file to eliminate struct padding. Default for VC++ is 8 byte boundary.

gcc and other compilers will have their own equivalents.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜