How to Find Size of Dynamic Array in C?
Last Updated :
11 Mar, 2024
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
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size = 5;
int * arr = ( int *) malloc (
size * sizeof ( int ));
for ( int i = 0; i < size; i++) {
arr[i] = i;
}
for ( int i = 0; i < size; i++) {
printf ( "%d " , arr[i]);
}
free (arr);
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...