In C language, we can calculate the size of the static array using the sizeof operator but there is no operator to calculate the size of the dynamically allocated memory. So using some trick we can get the size of the allocated array. Mainly there are two ways to get the size of allocated memory in every section of the code.
- Create a global variable to store the size of the allocated memory.
- Carry the length of allocated memory.
Let see an example code, where I am explaining how you can carry the length of the array. So suppose you need to create an integer array whose size is n. So to carry the array length of the array, you need to allocate the memory for n+1.
If memory is allocated successfully, assign n (size of the array) its 0 places.
Now it’s time to create a copy of the original pointer but to left one location from the beginning.
Now, whenever in a program you require the size of the allocated dynamic, you get from the temporary pointer(copy pointer).