How does a static array differ from a dynamic array?
A static array and a dynamic array differ in how and when memory is allocated to them and whether the array's size can change while the program is running.
1. Static array
- The size is set once, at creation time.
- Memory is allocated in advance (on the stack or in a fixed memory area).
- The number of elements cannot be changed: if more is needed, a new array must be created.
Example (C):
c
int a[5]; // an array of 5 elementsIf a 6th element is needed, it's impossible to add one, the array has to be recreated.
Pros:
- Simple structure.
- Fast access to elements.
- No memory reallocations.
Cons:
- The size cannot be changed.
- Extra memory may be wasted if allocated "with a margin".
2. Dynamic array
- The size can be changed at runtime.
- Memory is allocated on the heap as needed.
- On overflow, a new memory block is created and the elements are copied there.
Example (Python / C++):
python
arr = [1, 2, 3]
arr.append(4) # adding a new element(In C++ it's std::vector, in Java it's ArrayList.)
Pros:
- Flexibility: you can add and remove elements.
- The size grows automatically.
Cons:
- Sometimes all elements get copied during expansion (expensive in time).
- Less predictable memory usage.
3. Visually
Static:
javascript
[ ][ ][ ][ ][ ] ← fixed sizeDynamic:
javascript
[ ][ ][ ] → (overflowed) → creates [ ][ ][ ][ ][ ][ ] and copiesSummary:
A static array is fixed in size, fast and simple. A dynamic array is resizable and flexible, but sometimes spends time on memory reallocation.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.