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

x
  • 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?

Thanks.

0
JohnSantaFe
Asked:
JohnSantaFe
2 Solutions
 
stachenovCommented:
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.
0
 
ssnkumarCommented:
> 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:
http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf
0
 
JohnSantaFeAuthor Commented:
Thank you.
0

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