Introduction
• Dynamic MemoryAllocation (DMA) allows
programs to request memory at runtime.
• Useful for arrays whose size is not known at
compile time.
• Functions provided in C: malloc(), calloc(),
realloc(), free.
2.
malloc()
Stands for memoryallocation.
Syntax: ptr = (castType*) malloc(size_in_bytes);
Allocates a single block of memory.
Returns NULL if allocation fails.
Example:
int *arr;
arr = (int*) malloc(5 * sizeof(int));
if(arr == NULL) {
printf("Memory allocation failed");
}
3.
calloc()
Stands for contiguousallocation.
Syntax: ptr = (castType*) calloc(num_elements,
size_of_element);
Allocates memory and initializes to zero.
Example:
int *arr;
arr = (int*) calloc(5, sizeof(int));
4.
realloc()
Reallocates previously allocatedmemory.
Syntax: ptr = (castType*) realloc(ptr, new_size);
Preserves old data and adjusts memory size.
Example:
arr = (int*) realloc(arr, 10 * sizeof(int));
Pointer Arithmetic
Operators: +,-, ++, --
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("%d", *(ptr + 2)); // prints 30
Moving pointer by index multiplies by size of data type
7.
Pointers and Arrays
Arrayname as a pointer: arr ≡ &arr[0]
Access array using pointer arithmetic:
*(arr + i) // arr[i]
Sum of array elements using pointer:
int sum = 0;
for(int i=0;i<n;i++) sum += *(arr+i);
8.
1D Array UsingPointers
Allocate, initialize, and access elements.
Example:
int *arr = (int*) malloc(5 * sizeof(int));
for(int i = 0; i < 5; i++)
arr[i] = i+1;
for(int i = 0; i < 5; i++)
printf("%d ", arr[i]);
free(arr);
9.
2D Array UsingPointers
Allocate 2D array dynamically using pointers.
Example:
int **arr;
int rows = 3, cols = 4;
arr = (int**) malloc(rows * sizeof(int*));
for(int i = 0; i < rows; i++)
arr[i] = (int*) malloc(cols * sizeof(int));
// Initialize
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
arr[i][j] = i+j;
// Free memory
for(int i = 0; i < rows; i++) free(arr[i]);
free(arr);
10.
Pointer Arithmetic with1D Array
Access elements using pointers.
Example:
for(int i = 0; i < 5; i++)
*(arr + i) = i*2;
11.
Pointer Arithmetic with2D Array
Access elements using pointer arithmetic.
Example: *(*(arr + i) + j) = i + j;
12.
Pointers and Functions
Passby reference using pointers
Example: Swap two numbers
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
Call : swap(&x,&y);