Venkatesh
Venkatesh

Reputation: 1577

Struct size stays the same even after adding a new member to it

when is simply execute

cout << sizeof(string);

i got 8 as answer.

now i am having a structure

typedef struct {
    int a;
    string str;
} myType;

and i am executing

cout << sizeof(myType);

i got 16 as the answer.

now i made a change in my structure

typedef struct {
    int a, b;
    string str;
} myType;

and i am executing

cout << sizeof(myType);

i got 16 as the answer!!!. How? What is happening?

Upvotes: 0

Views: 245

Answers (4)

cabbi
cabbi

Reputation: 403

In C/C++ structs are "packed" in byte chunks. You can specify which size your structs should be packed. Here a reference: http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx

Upvotes: -2

Rob K
Rob K

Reputation: 8926

It's called structure packing to achieve optimal memory alignment.

See The Lost Art of C Structure Packing to understand the how and why. It's done the same way in both C and C++.

Upvotes: 0

AlexD
AlexD

Reputation: 32576

Perhaps padding is happening. E.g. sizeof(int) can be 4 bytes and compiler can add 4 bytes after a for the sake of data alignment. The layout could be like this:

typedef struct {
    int a;      // 4 bytes
                // 4 bytes for padding
    string str; // 8 bytes
} myType;

typedef struct {
    int a;      // 4 bytes
    int b;      // 4 bytes
    string str; // 8 bytes
} myType;

Upvotes: 7

Andreas Reiff
Andreas Reiff

Reputation: 8404

Looks like 8 byte alignment.

So if you have any data type that has less than 8 bytes, it will still use 8 bytes.

I assume the pointer is 8 byte, whereas the ints are only 4 bytes each.

You can force 1 byte alignment using code like outlined here Struct one-byte alignment conflicted with alignment requirement of the architecture? . You should then get different size for first case.

Upvotes: 0

Related Questions