Given
struct Foo {
uint32_t a;
uint32_t b[];
};
What is sizeof(Foo)
? Is it implementation-defined or undefined behaviour? Does the answer differ for C vs C++?
In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.
foo=sizeof(para)/sizeof(para[0]);
A struct always gets its size adjusted to be n times the member with the highest alignment requirement. If you have an 8-byte double in the struct, then the struct must be n*8 bytes large, so your first example will need four bytes of padding.
Flexible array members are a special type of array in which the last element of a structure with more than one named member has an incomplete array type; that is, the size of the array is not specified explicitly within the structure.
The compiler will ignore the flexible array member as it were not there.
C11-§6.7.2.1 (p18)
[...] In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply [...].
AFAIK, flexible array member is not the part of C++ standard till c++14. But, GNU support it as an extension. Behaviour will be similar for both C and C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With