Why does sizeof give me this result?

I have this code

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

Now i need to get sizeof s

so i added

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

now that i got the compilation, the result shows 256

and its wrong because it must be 253

since the size

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

and

floating class; -----> 4

and

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

and

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

therefore 48 + 4 + 200 + 1 = 253

so why does he tell me 256?

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

this part is written after I saw your answers

I found out 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 at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it hard for the processor, too. Therefore, most compilers will panel packed'' version, notice how it at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it hard for the processor, too. Therefore, most compilers will packed'' version, notice how it at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it hard for the processor, too. Therefore, most compilers will packed'' version, notice how it at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it hard for the processor, too. Therefore, most compilers will pad '' (as if with additional invisible fields):

 +-------+-------+-------+-------+ | a | pad1 | +-------+-------+-------+-------+ | b | pad2 | +-------+-------+-------+-------+ | c | +-------+-------+-------+-------+ | d | pad3 | +-------+-------+-------+-------+ 

therefore, if Im having a maximum size is 200, if the padding will look like

48 + 152

4 + 196

200 + 0

1 + 199

to make them fit

+4
source share
4 answers

There may be uppercase bytes between members of the structure or at the end of the structure.

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

+16
source

The compiler binds the structure to the word boundary. It is easier for a process to process pieces of size 256 bytes than an odd number, such as 253.

+3
source
 int marks[10,5]; 

it should be

 int marks[10][5]; 

Filling and alignment problems may also occur.

+2
source

If you are using Visual C ++, add #pragma pack(1) to the top of the source file to eliminate structure debugging. The default value for VC ++ is an 8-byte boundary.

gcc and other compilers will have their own equivalents.

+2
source

Source: https://habr.com/ru/post/1305247/


All Articles