Explanation
Allocate memory dynamically for one-dimensional arrays and multi-dimensional arrays using various functions. The most commonly used functions for memory allocation are ‘ malloc’, ‘calloc’, and ‘ ‘realloc ‘.
-
malloc (Memory Allocation):
-
malloc (memory allocation) is used to allocate a block of memory of a specified size. It returns a pointer to the first byte of the block, which can be used for storing data.
-
Example for a one-dimensional array:
int *array;
int size = 5; // Number of elements
array = (int *)malloc(size * sizeof(int));
if (array == NULL) {
// Memory allocation failed
exit(1);
}
Example for a two-dimensional array:
int **matrix;
int rows = 3;
int cols = 4;
matrix = (int **)malloc(rows * sizeof(int *));
if (matrix == NULL) {
// Memory allocation failed
exit(1);
}
for (int i = 0; i < rows; i++) {
matrix[i] = (int *)malloc(cols * sizeof(int));
if (matrix[i] == NULL) {
// Memory allocation failed
exit(1);
}
}
-
calloc (Contiguous Allocation):
-
calloc (contiguous allocation) is used to allocate memory for an array and initializes all its bytes to zero.
-
Example for a one-dimensional array:
int *array;
int size = 5; // Number of elements
array = (int *)calloc(size, sizeof(int));
if (array == NULL) {
// Memory allocation failed
exit(1);
}
realloc (Reallocate Memory):
-
realloc is used to resize an already allocated block of memory. It can be used to expand or shrink an existing memory block.
-
Example for resizing a one-dimensional array:
int *array;
int newSize = 10; // New number of elements
array = (int *)realloc(array, newSize * sizeof(int));
if (array == NULL) {
// Memory reallocation failed
exit(1);
}
Example for resizing a two-dimensional array (matrix):
int **matrix;
int newRows = 5; // New number of rows
matrix = (int **)realloc(matrix, newRows * sizeof(int *));
if (matrix == NULL) {
// Memory reallocation failed
exit(1);
}
Always check the return value of these allocation functions to ensure that the memory allocation was successful. If memory allocation or reallocation fails, these functions return a NULL pointer.
The dynamically allocated memory using the free function when you are done with it to avoid memory leaks:
free(array);
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
Dynamic memory allocation is useful when you need to work with data structures of variable or unknown size during program execution.