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.
The C programming language leverages the malloc() function to dynamically allocate memory for arrays, offering flexibility in managing memory resources at runtime. Here's an illustrative example showcasing this capability:
#include <stdio.h> #include <stdlib.h> int main() { int *array; int size; printf("Enter the desired 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 array elements for (int i = 0; i < size; i++) { array[i] = i * 10; // Example initialization } // Print array elements printf("Array elements: "); for (int i = 0; i < size; i++) { printf("%d ", array[i]); } printf("\n"); // Free allocated memory free(array); return 0; }
This program prompts the user to specify the desired size of the array dynamically. It then allocates memory accordingly using malloc(). Following initialization and printing of array elements, memory deallocation is performed via free(), ensuring efficient resource management and preventing memory leaks. The dynamic nature of malloc() empowers developers to adaptively manage memory allocation based on program requirements, enhancing the versatility and scalability of C applications.