0

I just tried to check how memory is allocated to structure objects, its taking more space what i expected. I am using 64 bit windows OS and Microsoft visual studio 2010(i think its 32 bit), so can some explain why is its printing 52 bytes ?

struct test {
  int year;// should take 4 byte
  string title;// how much bytes would take ? in my case taking 31 bytes ?
  double date;//should take 8 byte
  int month;// should take 4 byte
  } mine;

int main ()
{
 cout << " size is: "<<sizeof(mine);//printing 52 ?
 cout << " size is: "<<sizeof(struct test);//printing 52 ?
  return 0;
}
User
  • 619
  • 1
  • 9
  • 24

1 Answers1

1

Note that

sizeof(struct) >= sizeof(its members)

Because each member might be aligned to the lowest address after the previous member that satisfies:

mod(address/sizeof(member)) == 0

For example, consider this struct:

struct s {
   char c;
   int i[2];
   double d;
}

The memory might look like that:

+-------------------------------------------------+
| c |  |  |  | i[0] | i[1] |  |  |  |  | .. v ..  |
+-------------------------------------------------+
     ^  ^  ^                ^  ^  ^  ^
Maroun
  • 94,125
  • 30
  • 188
  • 241