Static Array
Static Arrays
1. Memory Allocation:
Static arrays are allocated on the stack.
The size of the array must be known at compile-time and cannot be changed
during runtime.
2. Syntax:
int arr[5]; // Static array of size 5
3. Lifetime:
Static arrays are automatically created and destroyed when their scope is entered
and exited (e.g., within a function).
4. Advantages:
Simplicity: Easy to declare and use.
Performance: Generally faster access since the memory is allocated on the stack.
5. Limitations:
Fixed Size: The size must be known and fixed at compile-time.
Stack Limit: Large static arrays can lead to stack overflow.
Example Program
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // Static array
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
return 0;
}
Dynamic Array
1. Memory Allocation:
Dynamic arrays are allocated on the heap.
The size can be determined at runtime.
2. Syntax:
int* arr = new int[5]; // Dynamic array of size 5
3. Lifetime:
The programmer is responsible for managing the lifetime of dynamic arrays. You
need to explicitly allocate and deallocate memory.
4. Advantages:
Flexible Size: You can create arrays of sizes that are not known until runtime.
Heap Storage: Allows for larger arrays compared to the stack.
5. Limitations:
Manual Memory Management: You need to use delete[] to deallocate the
memory, which can lead to memory leaks if not handled properly.
Potential Performance Overhead: Accessing heap memory can be slower
compared to stack memory.
Example Dynamic Array
#include <iostream>
using namespace std;
int main() {
int* arr = new int[5]; // Dynamic array
// Initialize the array
for (int i = 0; i < 5; i++) {
cin>>arr[i];
}
// Print the array
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
delete[] arr; // Deallocate the memory
return 0;
}