Search code examples
carraysmemory-managementdynamic-arrays

Dynamic Array in C


Array by definition is a chunk of contiguous memory locations. What i understand from Dynamic is that we can allocate memory at run time. So for Dynamic Array lets say we allocate 100 memory spaces at run time. Now we perform some other operation and allocate few memory spaces for other variables. Since the array we created was meant to be Dynamic so i suppose we can add more elements t it occupying more memory spaces. But what i fail to understand is how this is going to be contiguous because the next memory addresses are per-occupied and Arrays by definition are supposed to be Contiguous???


Solution

  • You are mixing terminologies. In C and C++ arrays are technically a sequence of contiguous elements of the same type. When using the term "dynamic array" you are not using a standard-mandated term, but a general computer science term, which refers to array-like containers whose size can change at runtime.

    In C++ these array-like containers are implemented, for example, through the vector class, available including the <vector> standard library header. In other languages there may be other facilities.

    C has no dynamic arrays, but you can allocate arrays dynamically. Here the term "dynamic" has a different meaning: it is related to the management of dynamic memory, which is what you do when you use malloc and free functions.

    In C++, dynamic arrays are implemented managing dynamic memory under the hood, but this is an implementation detail that has little to do with the terminology.

    Also in C you could implement dynamic arrays (for example writing a custom library), but their usage wouldn't be supported by the language syntax, as in C++.

    Whether or not the storage for a dynamic array (either in C++ or in C) is contiguous is, again, an implementation detail. If you need to have a dynamic array (general meaning) implemented as a C/C++ array (technical term), you will end up reallocating memory and copying elements around explicitly. The standard C library provides the realloc function to help coping with such a task.