Size of a structure is not the same as presumed!!!

C

chandanlinster

Consider the following program:

/*********************************************************************************/
#include <stdio.h>

int
main()
{
struct name_struct {
int i;
char ch;
};

printf("sizeof(struct name_struct) = %d\n", sizeof(struct
name_struct));

return 0;
}
/***********************************************************************************/

OUPUT
sizeof(struct name_struct) = 8


Since I am using a 32 bit compiler, the output according to me has to
be

sizeof(int) + sizeof(ch) = 4 + 1 = 5

why is the compiler allocating 3 extra bytes.?
Can anybody explain why this is happening.
 
R

Robert Gamble

chandanlinster said:
Consider the following program:

#include <stdio.h>

int
main()
{
struct name_struct {
int i;
char ch;
};

printf("sizeof(struct name_struct) = %d\n", sizeof(struct
name_struct));

return 0;
}

OUPUT
sizeof(struct name_struct) = 8

Since I am using a 32 bit compiler, the output according to me has to
be

sizeof(int) + sizeof(ch) = 4 + 1 = 5

why is the compiler allocating 3 extra bytes.?
Can anybody explain why this is happening.

<http://c-faq.com/>. See question 2.13.

Robert Gamble
 
G

Gordon Burditt

If the size of a structure doesn't match the specific integer
value you presumed, DON'T PRESUME THAT!

A compiler may add padding after every structure member, if it
wants to.
 
B

Barry Schwarz

Consider the following program:

/*********************************************************************************/
#include <stdio.h>

int
main()
{
struct name_struct {
int i;
char ch;
};

printf("sizeof(struct name_struct) = %d\n", sizeof(struct
name_struct));

Since sizeof evaluates to a size_t which can be different than int,
this can invoke undefined behavior. If your compiler does not have a
format for size_t then cast the result to a type it does support,
unsigned long is pretty popular.
return 0;
}
/***********************************************************************************/

OUPUT
sizeof(struct name_struct) = 8


Since I am using a 32 bit compiler, the output according to me has to
be

sizeof(int) + sizeof(ch) = 4 + 1 = 5

why is the compiler allocating 3 extra bytes.?
Can anybody explain why this is happening.


Remove del for email
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,781
Messages
2,569,619
Members
45,316
Latest member
naturesElixirCBDGummies

Latest Threads

Top