![]() |
VOOZH | about |
Structures and unions are essential user-defined data types in C, widely used in system-level programming, embedded development, memory-constrained applications, and low-level data manipulation. These questions test how well you understand memory layout, data handling, padding, alignment, and practical implementation scenarios.
A structure is a user-defined datatype that groups variables of different datatypes under a single name.
A union allows storing different datatypes in the same memory location. Only one value can be stored at a time, unlike structures where each member has its own memory.
Example:
struct S { int x; double y; }; // 4 + 8 = 12 (may round to 16 due to alignment)
union U { int x; double y; }; // 8
This tests structure arrays and user input handling.
Input:
Elon 42
Hisenberg 45
Output:
Elon 42
Hisenberg 45
Yes, C allows direct assignment because structures support copy semantics.
Because C does not perform byte-wise comparison of structure objects. You must compare field by field.
Padding is added by the compiler so members align correctly in memory for efficient CPU access.
Example:
struct A {
char c; // 1 byte
int x; // 4 bytes, but shifted to 4-byte boundary
};
Use #pragma pack(1) or compiler-specific attributes.
#pragma pack(1)
struct Data {
char c;
int x;
};
Yes, called nested structures.
struct Date { int d, m, y; };
struct Employee {
char name[20];
struct Date doj;
};
You get implementation-dependent garbage, except when using type punning with proper alignment rules.
Example:
union Test { int i; float f; };
Writing to i and reading f invokes type punning.
Bit-fields allow packing data in memory with specific bit widths-useful in embedded systems.
struct Flags {
unsigned int a : 1;
unsigned int b : 2;
unsigned int c : 5;
};
. is used with structure variables.
-> is used with structure pointers.
struct A { int x; };
struct A s = {10};
struct A *p = &s;printf("%d %d", s.x, p->x);
Variant types store data that may change type based on a tag (like in protocol parsers).