YAKOVM
YAKOVM

Reputation: 10153

actual structure size

How can I know the actual structure size? using sizeof returns the number of bytes after alignment. For example :

struct s {
               char c;
               int i
}

sizeof(s) = 8; I am interested to get the size of bytes without alignment ,i.e 5

Upvotes: 4

Views: 760

Answers (3)

egrunin
egrunin

Reputation: 25083

You have misunderstood the documentation.

using sizeof returns the number of bytes after alignment

This is incorrect. sizeof returns the number of bytes after padding, which is not the same thing.

Thus, if what you want to know is "how much space will my struct take", sizeof() is telling you the correct answer.

Upvotes: 0

Tom Tanner
Tom Tanner

Reputation: 9354

sizeof returns the actual structure size.

The size without padding is a bit meaningless, because the compiler will insert the padding it feels appropriate. Some compilers support pragmas that turn off structure padding, in which case you should use that, but you'll probably get all sorts of fun things happening.

Upvotes: 2

BigBoss
BigBoss

Reputation: 6914

The actual size of structure is size of structure after alignment. I mean sizeof return size of structure in the memory. if you want to have an structure that aligned on byte you should tell the compiler to do that. for example something like this:

#ifdef _MSVC
#  pragma pack(push)
#  pragma pack(1)
#  define PACKED
#else
#  define PACKED            __attribute((packed))
#endif
struct byte_aligned {
    char c;
    int i;
} PACKED;
#ifdef _MSVC
#  pragma pack(pop)
#endif

now sizeof(byte_aligned) return 5 and its actually 5 byte in memory

Upvotes: 8

Related Questions