C Programming: Structures and Unions

Tricky Questions on Structures and Unions

What is a structure in C and how does it differ from an array?
A struct is a user-defined data type that groups variables of different data types under a single name. Unlike arrays which store elements of the same type, structures can store heterogeneous data. Each element in a structure is called a member and is accessed using the dot operator.
struct Student {
  char name[50];
  int roll_no;
  float marks;
};
What is a union in C and how does it differ from a structure?
A union is similar to a structure but all members share the same memory location. The size of a union is equal to the size of its largest member. Only one member can contain a value at any given time. In contrast, structure members have separate memory locations.
Key Difference: Structures allocate memory for all members (sum of all members), while unions allocate memory equal to the largest member only.
What is the size of an empty structure in C?
In standard C, an empty structure has a size of 0 bytes. However, in many compilers (like GCC), an empty structure has a size of 1 byte to ensure that two different objects have different addresses. This is implementation-dependent behavior.
struct Empty {};
printf("Size: %lu\n", sizeof(struct Empty)); // Usually 1 in GCC
What is structure padding and why is it used?
Structure padding is the process of adding extra bytes between members to align data according to the processor's architecture. This improves memory access speed. The compiler adds padding to ensure that each member starts at an address divisible by its size or the processor's word size.
Important: Padding can make structures larger than the sum of their members. Use #pragma pack(1) to avoid padding (but may reduce performance).
What is the difference between . (dot) and -> (arrow) operators?
The . (dot) operator accesses structure members when working with structure variables. The -> (arrow) operator accesses structure members when working with pointers to structures. ptr->member is equivalent to (*ptr).member.
Can a structure contain a pointer to itself?
Yes, a structure can contain a pointer to itself. This is commonly used in linked lists, trees, and other dynamic data structures. However, a structure cannot contain an instance of itself (only a pointer to itself).
struct Node {
  int data;
  struct Node* next; // Pointer to same structure type
};
What is a bit field in a structure?
Bit fields allow structure members to be stored in bits rather than bytes, saving memory when variables require fewer bits than a full byte. They're defined using a colon followed by the number of bits.
struct Status {
  unsigned int error : 1; // 1 bit
  unsigned int ready : 1; // 1 bit
  unsigned int mode : 2; // 2 bits
};
Can we compare two structures using the == operator?
No, we cannot use the == operator to compare two structures directly. We must compare each member individually or use memcmp() function (but be careful with padding bytes).
Tricky Point: Even if two structures have identical member values, == comparison will fail because it compares addresses, not contents.
What is an anonymous union/structure?
An anonymous union/structure is one without a name. Members can be accessed directly without using the union/structure variable name. They're useful for nested structures where intermediate names aren't needed.
struct Outer {
  int type;
  union { // Anonymous union
    int int_val;
    float float_val;
  };
};
// Access: obj.int_val (not obj.union_name.int_val)
How are structures passed to functions - by value or by reference?
By default, structures are passed to functions by value (a copy is made). This can be inefficient for large structures. To pass by reference, use pointers. For efficiency, always pass large structures using pointers.
void funcByValue(struct Student s); // Pass by value (copy)
void funcByRef(struct Student *s); // Pass by reference
Can a union be a member of a structure and vice versa?
Yes, a union can be a member of a structure, and a structure can be a member of a union. This allows creating complex data types with flexible memory usage.
struct S { int x; float y; };
union U {
  struct S s_var;
  char arr[8];
};
What is a flexible array member in a structure?
A flexible array member is an array without a specified size as the last member of a structure. It allows structures to have variable length. Memory must be allocated dynamically using malloc() with extra space for the array.
struct FlexArray {
  int length;
  int data[]; // Flexible array member
};
struct FlexArray *fa = malloc(sizeof(struct FlexArray) + n * sizeof(int));
What is the difference between typedef struct and struct?
struct creates a structure type that must be referenced with the struct keyword. typedef struct creates an alias, allowing you to use the structure without the struct keyword.
struct Point1 { int x; int y; };
struct Point1 p1; // Need 'struct' keyword

typedef struct { int x; int y; } Point2;
Point2 p2; // No 'struct' keyword needed
Can we have a function inside a structure in C?
No, C structures cannot contain functions (methods) as members. However, you can include function pointers within structures to simulate object-oriented behavior. C++ allows functions in structures, but not standard C.
struct Calculator {
  int (*add)(int, int); // Function pointer
  int (*subtract)(int, int);
};
What happens when you assign one structure to another?
When you assign one structure to another (struct2 = struct1), all members are copied byte-by-byte (shallow copy). If the structure contains pointers, only the pointer addresses are copied, not the data they point to.
Warning: Structure assignment doesn't create deep copies of pointer members. For deep copying, you need to manually copy pointed data.
What is the alignment requirement of structures?
Structure alignment follows the alignment requirement of its most strictly aligned member. The entire structure is padded to be a multiple of this alignment. Alignment is typically the largest primitive type size in the structure (e.g., 8 for double on 64-bit systems).
Can we have a static member in a structure?
No, C structures cannot have static members. All structure members share the same storage characteristics (automatic by default). However, you can have a static variable of structure type.
Tricky Point: Unlike C++, C doesn't support static members within structures. Each structure instance has its own copy of all members.
What is a self-referential structure?
A self-referential structure contains a pointer to a structure of the same type. This is fundamental to linked data structures like linked lists, trees, and graphs.
struct ListNode {
  int data;
  struct ListNode* next; // Self-referential pointer
};
How can we initialize a structure?
Structures can be initialized during declaration using curly braces. C99 allows designated initializers to initialize specific members by name. Unspecified members are initialized to zero.
// Traditional initialization
struct Student s1 = {"John", 101, 85.5};

// Designated initializer (C99)
struct Student s2 = {.name = "Alice", .marks = 90.0, .roll_no = 102};

// Partial initialization (rest are zero)
struct Student s3 = {.name = "Bob"};
What are the practical uses of unions?
Unions are used for: 1) Type punning (interpreting same memory as different types), 2) Implementing variant types, 3) Saving memory in embedded systems, 4) Hardware register access, 5) Protocol parsing where data format varies.
union Data {
  int i;
  float f;
  char str[20];
};
// Same memory can store int, float, or string
What is the sizeof() a structure containing a union?
The size of a structure containing a union is the sum of sizes of all non-union members plus the size of the union (which is the size of its largest member), plus any padding for alignment.
Can we have an array of structures?
Yes, we can create arrays of structures just like arrays of primitive types. This is commonly used for databases, tables, and collections of records.
struct Student class[50]; // Array of 50 Student structures
class[0].roll_no = 101; // Access first student
What is forward declaration of a structure?
Forward declaration declares a structure without defining its members. It tells the compiler "this structure exists" when the full definition isn't available yet. Useful for circular dependencies and opaque pointers.
struct Node; // Forward declaration
struct List {
  struct Node* head; // Can use pointer to forward-declared struct
};
// Full definition later
struct Node { int data; struct Node* next; };
What happens if you write to one member of a union and read from another?
Writing to one member of a union and reading from another is called "type punning." It's implementation-defined and may lead to undefined behavior due to different representations of data types. Some compilers support it as an extension.
Warning: Type punning through unions is not strictly portable in standard C, though many compilers allow it.
How can we return a structure from a function?
Structures can be returned from functions by value (a copy is returned) or by pointer (returning address of static/local structure). Since C99, we can also return structure literals.
// Return by value
struct Point makePoint(int x, int y) {
  struct Point p = {x, y};
  return p;
}

// Return by pointer (must ensure memory persists)
struct Point* createPoint(int x, int y) {
  struct Point *p = malloc(sizeof(struct Point));
  p->x = x; p->y = y;
  return p;
}
Note: Structures and unions are fundamental for creating complex data types in C. Understanding memory layout, padding, and the differences between structures and unions is crucial for efficient programming and acing technical interviews.
Previous Structures and Unions Next