Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 451
  • Last Modified:

size of structure member

I know that sizeof() doesn't necessarily return the sum of the sizes for all the structure members because of byte alignment issues.  However, does sizeof() return the correct size when called on the individual members of the structure?  Is this portable?

typedef struct {
    uint8_t a;
    uint16_t b;
    uint32_t c;
} mystruct;

mystruct mystruct;
size_t size;

size = sizeof(mystruct.b)

Will size always equal 2 bytes?


2 Solutions
Genereally yes, but you should consider the following:

1. The uint16_t type is only required to exist when there is a native type that is exactly 16 bits long.

2. The sizeof operator returns size in chars, not bytes. The char type itself is only required to be at least 8 bits, but not exactly.

Therefore, on some rare and crazy, but nevertheless conforming to the standard, architectures, you may get the following problems:

1. If there is no native 16-bit type, it may even not compile.

2. If char size is more than 8 bits, you won't get the size in bytes (octets).

I once tried to figure out if any of such architectures actually exist, but was unable to found any. However, I can imagine some sort of special computer where char is 32 or 64 bits, and there are simply no smaller types supported by the CPU.
> size = sizeof(mystruct.b)
> Will size always equal 2 bytes?

int8_t, int16_t and int32_t are optional types.
So, your OS may define them or may not define them and hence they are not portable.

Look at the page# 256 of the ISO standard regarding this:
JohnSantaFeAuthor Commented:
Thank you.

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now