💻 Unit 4 – Part A (2-Mark Q&A)

Programming in C

⬅ Back to Unit 4

Ad Space

Part A: Structures and Unions

25) What is a self-referential structure?

A structure that contains a pointer to its own type. It enables linked data structures (lists, trees, graphs).

typedef struct Node{
    int data;
    struct Node *next;   // self-reference
} Node;

Without a pointer member, you can’t chain nodes together for dynamic collections.

26) Compare a structure with a union.

AspectStructureUnion
MemorySum of all membersSize of largest member (shared)
Active membersAll members valid at onceOnly the last written member is valid
Use-caseRecords with many fieldsVariant data / memory saving
ExampleStudent recordToken that may be int/float/char*
struct S{ int i; float f; };   // sizeof(S) ≈ 8
union  U{ int i; float f; };   // sizeof(U) = 4 (on 32-bit)

27) Structure vs Union (extra points)

28) What is typedef struct in C?

typedef creates an alias for a type. With struct it shortens declarations.

typedef struct Student{
    int id; char name[32];
} Student;                // alias = Student

Student s1;              // no need to write 'struct Student'

Helps readability and portability (change once in typedef).

29) What is meant by structure? Give an example.

A user-defined composite type grouping heterogeneous fields under one name.

struct Point{ int x; int y; };
struct Point p = {10, 20};
printf("%d,%d", p.x, p.y);

Used for records, coordinates, complex numbers, etc.

30) Can C allocate memory dynamically? Justify.

Yes. C provides malloc, calloc, realloc, and free in <stdlib.h> to manage heap memory at runtime.

#include <stdlib.h>
int *a = malloc(n * sizeof *a);
if(!a){ /* handle failure */ }
a = realloc(a, m * sizeof *a);
free(a);

Essential when data size is unknown until execution (e.g., reading a file, building lists).

31) List operations on structures.

struct Emp{int id; char name[16];};
void printEmp(const struct Emp *e){ printf("%d %s", e->id, e->name); }

32) Interpret the term union in C.

A union stores different types in the same memory location; only one member is meaningful at a time. Useful for variant records, protocol packets, or memory-constrained embedded code.

union Token{
    int    ival;
    float  fval;
    char  *sval;
} t;
t.fval = 3.14f;          // last written member = active

Always track which member is active (e.g., with an enum tag).

Ad Space