Ad Space
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.
| Aspect | Structure | Union |
|---|---|---|
| Memory | Sum of all members | Size of largest member (shared) |
| Active members | All members valid at once | Only the last written member is valid |
| Use-case | Records with many fields | Variant data / memory saving |
| Example | Student record | Token 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)
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).
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.
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).
. for objects, -> for pointers.struct Emp{int id; char name[16];};
void printEmp(const struct Emp *e){ printf("%d %s", e->id, e->name); }
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