Structure Query....

S

Sachin

typdef struct
{
int i;
char ch;
}str;
str str_var;
char x, y;
main()
{
//do nothing
}

In the above piece of code the structure needs a padding of 3 more
bytes (the total size of the structure variable being 8 bytes). Now
my question is, wont the compiler append x & y to the end of structure
and adds just 1 byte as the padding?
In my case I use MSVC compiler. When I checked the size of obj in the
map file the obj size was 12 bytes....shouldnt it be 8 bytes ideally??

Thanks in advance...
Regds
Sachin
 
J

Jens.Toerring

Sachin said:
typdef struct
{
int i;
char ch;
}str;
str str_var;
char x, y;
main()

int main( void )
{
//do nothing
}
In the above piece of code the structure needs a padding of 3 more
bytes (the total size of the structure variable being 8 bytes). Now
my question is, wont the compiler append x & y to the end of structure
and adds just 1 byte as the padding?

First of all, the compiler is entitled to add as much padding as
it wants, so you should never rely on a certain value. Second,
you can't know if the compiler will put x and y at a certain place
in relation to the structure, it could put the before or after the
structure or somewhere completely different. Third, even if both
these variable would come directly after the structure in memory
the structure would still have its full padding - if different
padding would be used dependening on circumstances the value of
'sizeof( struct str )' wouldn't be welldefined. And imagine what
would happen then if you define another such structure and do

memcpy( &str_var, &another_str_struct, sizeof( struct str ) );
In my case I use MSVC compiler. When I checked the size of obj in the
map file the obj size was 12 bytes....shouldnt it be 8 bytes ideally??

No idea what "size of obj in the map file" is, but you can simply
get the size with the sizeof operator. But the compiler is still
free to add as much padding as it likes to (or thinks necessary).
If that's a different value from what you think is necessary you
have to discuss that with the people that wrote the compiler, it
is nothing the C standard specifies.

Regards, Jens
 
B

Ben Pfaff

typdef struct
{
int i;
char ch;
}str;
str str_var;
char x, y;
main()
{
//do nothing
}

In the above piece of code the structure needs a padding of 3 more
bytes (the total size of the structure variable being 8 bytes). Now
my question is, wont the compiler append x & y to the end of structure
and adds just 1 byte as the padding?

No. Then the following:
memset (&str_var, 0, sizeof str_var);
would clear x and y as well as str_var.
 

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,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top