Data Structures in C - Detailed Notes
1. Structure Definition in C
A structure in C is a user-defined data type that allows grouping variables of different data types under a single name.
Syntax:
struct Student {
int id;
char name[50];
float marks;
};
2. Structure Initialization
Structures can be initialized at the time of declaration.
Example:
struct Student s1 = {101, "Anjali", 89.5};
Access members: s1.id, s1.name
3. Array as Structure
An array of structures allows storing multiple records of the same structure type.
Example:
struct Student students[5];
4. Array within Structure
A structure can contain arrays as its members to store strings or multiple values.
Example:
struct Student { char name[30]; };
Data Structures in C - Detailed Notes
5. Union in C
A union shares memory among its members; only one can hold a value at a time.
Example:
union Data { int i; float f; char str[20]; };
6. Understanding Pointers
A pointer is a variable that stores the address of another variable.
Example:
int a = 10; int *p = &a;
7. Declaring and Initializing Pointers
Declare with * and initialize with the address of a variable.
Example:
int *ptr = &x;
8. Accessing a Variable Through Pointer
Use * (dereferencing) to access the value stored at a pointer's address.
Example:
*ptr returns the value of x.
9. Static Memory Allocation
Memory is allocated at compile time. Size is fixed.
Example:
Data Structures in C - Detailed Notes
int arr[10];
10. Dynamic Memory Allocation
Memory allocated at runtime using malloc, calloc, etc.
Example:
int *ptr = (int *)malloc(5 * sizeof(int));
free(ptr);