Verified Solution & Step-by-Step Explanation
solution · en · Verified by Editorial Board
Dynamic Memory Allocation in C
Dynamic memory allocation allows programs to request memory from the operating system heap during runtime rather than compile time.
malloc() vs calloc()
malloc(size): Allocates a single contiguous block of memory of specified bytes. Contains garbage values.calloc(n, size): Allocatesnblocks of memory, each ofsizebytes, and initializes all allocated bytes to zero.
```c #include <stdio.h> #include <stdlib.h>
int main() { int n, temp; printf("Enter number of elements: "); scanf("%d", &n);
int arr = (int) malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; }
printf("Enter %d integers:\n", n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); }
// Bubble Sort for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }
printf("Sorted array in ascending order:\n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n");
free(arr); // Deallocate arr = NULL; return 0; } ```
