• + 1 comment

    In c lanuange when we can declare array only using a constant like int arr[5], but not using varible int arr[n],so when we dont know size of array at compile time we use a pointers and malloc/calloc function to get memory at runtime. Here memory is allocated in heap instead of stack.

    However c99 standard introduces Variable Length Arrays(VLA) in C so you need not use dynamic memory allocation just because you do not know the array dimensions before hand. you can declare it normally like int arr[n] but still most of Competitive exams and college exams follow old protocols so we need to learn it.

    You should use dynamic memory when:

    If you want your object to persist beyond the scope in which it was created. Usually, stack sizes are limited and hence if your object occupies a lot of memory then you might run out of stack space in such cases one would usually go for dynamic memory allocation.

    If you want your object to persist beyond the scope in which it was created. Usually, stack sizes are limited and hence if your object occupies a lot of memory then you might run out of stack space in such cases one would usually go for dynamic memory allocation.