sizeof()

J

junw2000

For the structure below:

struct A{
int a;
double b;
char c;

};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?

Thanks.

Jack
 
J

Jakob Bieling

For the structure below:

struct A{
int a;
double b;
char c;

};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?

What do you expect? The compiler is free to add padding bytes
between the members of the struct. So if you expected less, the rest is
probably padding.

hth
 
S

Scott McPhillips [MVP]

For the structure below:

struct A{
int a;
double b;
char c;

};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?

Thanks.

Jack

Compilers are free to insert unused space in a struct to optimize
hardware access to the struct members. In some machines, for example,
it is not possible to directly access a char unless it is aligned on a 4
or 8 byte boundary.
 
K

Kai-Uwe Bux

For the structure below:

struct A{
int a;
double b;
char c;

};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?

You probably know (or have read in the other replies) that there can be
padding within a struct. So, I will assume that you are just puzzled as to
why there could be padding at the *end* of a struct (behind the char).

I would conjecture that the compiler does this, so that when you allocate an
array

A* a = new A [12];

the elements of this array will be aligned properly. Very likely, int or
double needs to start on a word boundary on your implementation.



Best

Kai-Uwe Bux
 
R

Rolf Magnus

For the structure below:

struct A{
int a;
double b;
char c;

};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?

Why not?
 
M

Michiel.Salters

Scott said:
Compilers are free to insert unused space in a struct to optimize
hardware access to the struct members. In some machines, for example,
it is not possible to directly access a char unless it is aligned on a 4
or 8 byte boundary.

You just happened to pick the one type for which it isn't a problem.

Basically, an alignment requirement of A is never bigger than
sizeof(A),
because else an array of A is impossible. E.g. in a char[20], you can't
have every char aligned at a 4-byte border. &element[1]=1+&element[0].

Now, sizeof(short) might be 4, in which case that can have an alignment
restriction, but sizeof(char) is always 1.

HTH,
Michiel Salters
 

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,777
Messages
2,569,604
Members
45,235
Latest member
Top Crypto Podcasts_

Latest Threads

Top