Ask Questions Get Answers
In C, the malloc() function is utilized to dynamically allocate memory for an array. This process enables the creation of arrays whose size is determined during runtime rather than compile time. Consider the following example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array;
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
// Dynamically allocate memory for the array
array = (int *)malloc(size * sizeof(int));
if (array == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
// Initialize the array elements
for (int i = 0; i < size; i++) {
array[i] = i * 10; // Just an example initialization
}
// Access and print the array elements
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
// Free the allocated memory
free(array);
return 0;
}
This program prompts the user to input the size of the array. It then allocates memory for the array dynamically using malloc(). After initializing and printing the array elements, it deallocates the memory using free() to avoid memory leaks. Dynamic memory allocation with malloc() provides flexibility in managing memory resources, especially when dealing with arrays of varying sizes at runtime.