C Language Notes
Unit 4: Pointers and Dynamic Memory Allocation in C
1. Pointers:
- A pointer is a variable that stores the address of another variable.
- Declaration:
data_type *pointer_name;
Example:
int x = 10;
int *ptr = &x; // ptr holds the address of x
- Uses of Pointers:
a. Accessing memory locations.
b. Dynamic memory allocation.
c. Call by reference in functions.
2. Dynamic Memory Allocation:
- Allocates memory at runtime using functions from <stdlib.h>:
- malloc(): Allocates memory and returns a void pointer.
- calloc(): Allocates memory for an array and initializes it to 0.
- realloc(): Resizes previously allocated memory.
- free(): Frees allocated memory.
Example:
int *ptr = (int*)malloc(sizeof(int) * 5); // Allocates memory for 5 integers.
Page 1
C Language Notes
3. Pointer Arithmetic:
- Pointers support arithmetic operations like addition and subtraction to navigate memory.
Pointers and dynamic memory management provide powerful tools for system-level programming.
Page 2