In C, dynamic memory allocation allows us to manage memory resources during the execution of a program. It’s particularly useful when dealing with arrays where the size isn’t known at compile time. In this article, we will learn how to find the size of a dynamically allocated array in C.
Find Size of a Dynamically Allocated Array in C
When we dynamically allocate an array using the malloc
, calloc
, or realloc
functions, the size of the array isn’t stored anywhere in memory. Therefore, there’s no direct way to find the size of a dynamically allocated array. To manage the size of a dynamically allocated array, we must keep track of the size separately.
C Program to Keep the Track of Dynamically Allocated Array
The below program demonstrates how we can keep track of the size of a dynamically allocated array in C.
// C program to illustrate how to keep track of dynamically // allocated array #include <stdio.h> #include <stdlib.h> int main()
{ int size = 5; // size of the array
int * arr = ( int *) malloc (
size * sizeof ( int )); // dynamically allocated array
// fill the array
for ( int i = 0; i < size; i++) {
arr[i] = i;
}
// print the array
for ( int i = 0; i < size; i++) {
printf ( "%d " , arr[i]);
}
free (arr); // free the array to avoid memory leak
return 0;
} |
0 1 2 3 4
Note: In C, it’s generally recommended to use structures or linked lists when you need to keep track of the size of a dynamically allocated array during runtime. This provides more flexibility and control over the memory.