Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof giving me this result?

Tags:

c++

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 because 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

like image 489
hiba salem Avatar asked Nov 28 '22 19:11

hiba salem


1 Answers

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.

like image 143
James McNellis Avatar answered Dec 10 '22 22:12

James McNellis