sizeof struct with one member

May 30, 2011 at 7:01pm
hi everyone...
I've got a question aboute sizeof a struct in C++.
I am reading Stroustrup's book and it is said that the sizeof a struct not necessarily equals the sum of its members because of padding right?
My question is what happens if I declare a struct with one integer member like this:

1
2
3
4
struct S
{
 int i;
};


Could I state that sizeof(S) == sizeof(int)?
Or should it be sizeof(S)>= sizeof(int)?
I don't know what happens with this rule for structures with one member. I beleive no padding should be made but I don't really know if that is right.
Thanks in advance!
May 30, 2011 at 7:40pm
Test it. I hate filling my HDD with test projects, so I use ideone.com for those.

Most compilers will tell you, though that sizeof(S) in fact =='s sizeof(int). Normally, padding goes in multiples of the architecture's width.

You should be able to control the padding, though with #pragma pack.

Without testing it, I would say that:

1
2
3
4
5
6
7
8
9
10
11
12
struct S
{
    char c;
};

#pragma pack(1)
struct SS
{
    char c;
};

//I bet that sizeof(S) == sizeof(int), but sizeof(SS) == sizeof(char). 
May 30, 2011 at 8:01pm
thanks for your answer. I had already tested it when I asked this question.
The result was sizeof(S) == sizeof(int) of course.
But the standard says this depends on the architecture so my question goes beyond the practical test of this case.

I'll try to make my question clearer.
Given:
1
2
3
4
5
6
7
8
9
struct S
{ 
  int i;
};
struct S2
{
  int i;
  char c;
};


I know from the Standard that sizeof(S2) >= sizeof(int) + sizeof(char) for any architecture. That is something that is for sure.
My doubt arises when the struct has only one member. Could it happen in an "X" architecture that sizeof(S) > sizeof(int) ?
Last edited on May 30, 2011 at 8:02pm
May 30, 2011 at 8:14pm
Yes, when you have a struct containing a single field of type double, for example, or long long int.
Topic archived. No new replies allowed.