The Wayback Machine - https://web.archive.org/web/20240923165308/https://www.geeksforgeeks.org/difference-between-static-arrays-and-dynamic-arrays/
Open In App

Difference between Static Arrays and Dynamic Arrays

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept.

Types of Arrays:

There are basically two types of arrays:

  • Static Array: In this type of array, memory is allocated at compile time having a fixed size of it. We cannot alter or update the size of this array.
  • Dynamic Array: In this type of array, memory is allocated at run time but not having a fixed size. Suppose, a user wants to declare any random size of an array, then we will not use a static array, instead of that a dynamic array is used in hand. It is used to specify the size of it during the run time of any program.

Example:

Let us take an example, int a[5] creates an array of size 5 which means that we can insert only 5 elements; we will not be able to add 6th element because the size of the array is fixed above.

C++




int a[5] = {1, 2, 3, 4, 5}; //Static Integer Array
int *a = new int[5]; //Dynamic Integer Array


Java




import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        //  Static Array
        int[] staticArray = new int[5];
        int[] numbers = { 1, 2, 3, 4, 5 };
        // Dynamic Array
        // Create an ArrayList of integers.
        ArrayList<Integer> dynamicArray = new ArrayList<>();
 
        // Add elements to the dynamic array.
        dynamicArray.add(1);
        dynamicArray.add(2);
        dynamicArray.add(3);
 
        // Remove an element from the dynamic array.
        dynamicArray.remove(1);
    }
}


Python




# Static List
a_static = [1, 2, 3, 4, 5]
 
# Dynamic List (equivalent to dynamic array in some contexts)
a_dynamic = [0] * 5  # Initialize with zeros, similar to new int[5] in C++
 
# Alternatively, you can use the list() constructor to create a dynamic list
a_dynamic_alternative = list(range(5))
 
# Print the lists
print("Static List:", a_static)
print("Dynamic List:", a_dynamic)
print("Dynamic List (alternative):", a_dynamic_alternative)
 
# Coded By Block_Cipher


C#




using System;
 
class Program
{
    static void Main(string[] args)
    {
        // Static List
        int[] a_static = { 1, 2, 3, 4, 5 };
 
        // Dynamic List (equivalent to dynamic array in some contexts)
        int[] a_dynamic = new int[5]; // Initialize with default values (0 for int), similar to new int[5] in C#
 
        // Alternatively, you can use a loop to initialize the dynamic list
        int[] a_dynamic_alternative = new int[5];
        for (int i = 0; i < a_dynamic_alternative.Length; i++)
        {
            a_dynamic_alternative[i] = i;
        }
 
        // Print the lists
        Console.Write("Static List: ");
        PrintArray(a_static);
         
        Console.Write("Dynamic List: ");
        PrintArray(a_dynamic);
 
        Console.Write("Dynamic List (alternative): ");
        PrintArray(a_dynamic_alternative);
    }
 
    // Method to print an array
    static void PrintArray(int[] arr)
    {
        foreach (int item in arr)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
    }
}


Javascript




// Static Integer Array
const staticArray = [1, 2, 3, 4, 5];
 
// Dynamic Integer Array (Array with size allocation)
const dynamicArray = new Array(5); // Allocating memory for 5 elements
 
// Initializing dynamic array elements
for (let i = 0; i < dynamicArray.length; i++) {
    dynamicArray[i] = i + 1; // Assigning values 1, 2, 3, 4, 5
}
 
// Printing Static Integer Array
console.log("Static Integer Array:");
console.log(staticArray.join(" "));
 
// Printing Dynamic Integer Array
console.log("Dynamic Integer Array:");
console.log(dynamicArray.join(" "));


The code mentioned above demonstrates the declaration and initialization of both a static integer array and a dynamic integer array. Let’s break it down line by line:

Example of Static Array: int a[5] = {1, 2, 3, 4, 5};

  • A static integer array named a and initializes with the values 1, 2, 3, 4, and 5.
  • The size of this array is determined automatically based on the number of values provided in the initialization list.
  • Thus the array a is allocated on the stack, and its size cannot be changed once defined.

Example of Dynamic Array: int *a = new int[5];

  • In this code, we declare a pointer to an integer named a and it allocates memory in a dynamic fashion for an integer array of size 5.
  • The new keyword here is used for dynamic memory allocation, and int[5] specifies the size of this dynamic array.
  • The new operator is used to return the address of the dynamically allocated memory, which is already stored in the pointer a.
  • This array a is allocated on the Heap, and its size can be modified later if needed.

The differences between static and dynamic arrays based on this code snippet can be as followed:

Static Integer Array:

  • The size is determined automatically based on the number of values provided during initialization (in this case, 5).
  • The memory is allocated on the stack.
  • The size of the array is fixed once it is defined.

Dynamic Integer Array:

  • The memory is allocated during the run time by using the new keyword.
  • The size is specified explicitly (in this case, 5).
  • The memory is allocated on the heap (not the stack).
  • We can change the size of the array later by using delete[ ] which is used to to deallocate the memory and allocating a new block with a different size if desired.

Pictorial Representation of Static and Dynamic Arrays:
static

Static Array and Dynamic Array

Key Difference between Static and Dynamic Arrays:

Static Array

Dynamic Array

1. The memory allocation occurs during compile time.

1. The memory allocation occurs during run time.

2. The array size is fixed and cannot be changed.

2. The array size is not fixed and can be changed.

3. The location is in Stack Memory Space.

3. The location is in Heap Memory Space.

4. The array elements are set to 0 or to empty strings.

4. The array elements can be destroyed during erase statement and the memory is then released.

5. This array can be Initialized but not erased.

5. This array cannot be read or written after destroying.



Similar Reads

Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
Static and Dynamic Data Structures
Data structures are the fundamental building blocks of computer programming. They determine how data is organized, stored, and manipulated within a software application. There are two main categories of data structures: static and dynamic. Static data structures have a fixed size and are allocated in memory during compile-time, while dynamic data s
9 min read
Static and Dynamic Scoping
The scope of a variable x in the region of the program in which the use of x refers to its declaration. One of the basic reasons for scoping is to keep variables in different parts of the program distinct from one another. Since there are only a small number of short variable names, and programmers share habits about naming of variables (e.g., I fo
6 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Difference between a Static Queue and a Singly Linked List
Static Queue: A queue is an ordered list of elements. It always works in first in first out(FIFO) fashion. All the elements get inserted at the REAR and removed from the FRONT of the queue. In implementation of the static Queue, an array will be used so all operation of queue are index based which makes it faster for all operations except deletion
15+ min read
Difference between Recursion and Dynamic Programming
Recursion and Dynamic programming are two effective methods for solving big problems into smaller, more manageable subproblems. Despite their similarities, they differ in some significant ways. Below is the Difference Between Recursion and Dynamic programming in Tabular format:Features Recursion Dynamic Programming Definition By breaking a difficul
5 min read
Difference between Brute Force and Dynamic Programming
Brute Force: It gives a solution to a problem by using the most straightforward method. However, it is typically not a very optimal solution or one that is flexible for future changes, but it gets the job done. The proverbial brute force programming example is trying all optimal solutions for reaching the final answer.Brute force programming tests
6 min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
How do Dynamic arrays work?
A Dynamic array (vector in C++, ArrayList in Java) automatically grows when we try to make an insertion and there is no more space left for the new item. Usually the area doubles in size. A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required. The elements of
15+ min read
What will happen if i declare main() in java as non-static?
main() method in Java acts as an application's entry point. So declaration must read "public static void main(String[] args)" to work properly . What happens if you declare main to be non-static is as follows? Java Code import java.util.Scanner; public class Sample{ public void main(String[] args){ System.out.println(&amp;quot;This is a sample code
4 min read
CSES Solutions – Static Range Sum Queries
Given an array arr[] of N integers, your task is to process Q queries of the form: what is the sum of values in range [a,b]? Examples Input: arr[] = {1, 3, 4, 8, 6, 1, 4, 2}, Queries: {{2, 5}, {1, 3}}Output: 21 8Explanation: Query 1: Sum of elements from index 2 to 5 = 3 + 4 + 8 + 6 = 21Query 2: Sum of elements from index 1 to 3 = 1 + 3 + 4 = 8Inpu
5 min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm
Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms: Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.Divide and conquer algorithm: Breaks down a probl
4 min read
Count of elements such that difference between sum of left and right sub arrays is equal to a multiple of k
Given an array arr[] of length n and an integer k, the task is to find the number of indices from 2 to n-1 in an array having a difference of the sum of the left and right sub arrays equal to the multiple of the given number k. Examples: Input: arr[] = {1, 2, 3, 3, 1, 1}, k = 4 Output: 2 Explanation: The only possible indices are 4 and 5 Input: arr
7 min read
What is the difference between lists and arrays?
In programming, lists and arrays are data structures used to organize and store data. Both have their unique features and purposes. Lists are dynamic and flexible, allowing for easy resizing during runtime, while arrays are static with a fixed size. This difference impacts memory usage and performance. Table of Content What are Lists?What are Array
8 min read
Maximum sum of a subsequence having difference between their indices equal to the difference between their values
Given an array A[] of size N, the task is to find the maximum sum of a subsequence such that for each pair present in the subsequence, the difference between their indices in the original array is equal to the difference between their values. Examples: Input: A[] = {10, 7, 1, 9, 10, 15}, N = 6Output: 26Explanation: Subsequence: {7, 9, 10}. Indices
5 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is d
12 min read
Implement dynamic deque using templates class and a circular array
The task is to implement a dynamic Deque using templates class and a circular array, having the following functionalities: front(): Get the front item from the deque.back(): Get the last item from the deque.push_back(X): Push X at the end of the deque.push_front(X): Push X at the start of the deque.pop_front(): Delete an element from the start of t
9 min read
Implement dynamic queue using templates class and a circular array
In this article, we will discuss how to create a dynamic circular queue using a circular array having the following functionality: Front(): Get the front item from the queue.Back(): Get the last item from the queue.Push(X): Push the X in the queue at the end of the queue.Pop(): Delete an element from the queue. Below is the step-by-step illustratio
7 min read
Minimum moves to make M and N equal by repeated addition of divisors except 1 using Dynamic Programming
Given two integers N and M, the task is to calculate the minimum number of moves to change N to M, where In one move it is allowed to add any divisor of the current value of N to N itself except 1. Print "-1" if it is not possible. Example: Input: N = 4, M = 24Output: 5Explanation: The given value of N can be converted into M using the following st
8 min read
Divide and Conquer Optimization in Dynamic Programming
Dynamic programming (DP) is arguably the most important tool in a competitive programmer's repertoire. There are several optimizations in DP that reduce the time complexity of standard DP procedures by a linear factor or more, such as Knuth's optimization, Divide and Conquer optimization, the Convex Hull Trick, etc. They are, of paramount importanc
15+ min read
Introduction and Dynamic Programming solution to compute nCr%p
Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is to first compute nCr, then compute nCr % p. This s
15+ min read
Bitmasking and Dynamic Programming | Travelling Salesman Problem
In this post, we will be using our knowledge of dynamic programming and Bitmasking technique to solve one of the famous NP-hard problem "Traveling Salesman Problem".Before solving the problem, we assume that the reader has the knowledge of DP and formation of DP transition relationBitmasking in DPTraveling Salesman problem To understand this concep
15+ min read
Dynamic Programming (DP) and Directed Acyclic Graphs (DAG)
Pre-Requisite:What is Directed Graph? | Directed Graph meaningDynamic Programming (DP) Tutorial with Problems Every Dynamic Programming problem can be represented as a Directed Acyclic Graph(DAG). The nodes of the DAG represent the subproblems and the edges represents the transitions between the subproblems. Table of Content Relationship Between Dy
15+ min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Count of possible arrays from prefix-sum and suffix-sum arrays
Given 2*N integers which are elements of a prefix and suffix array(in shuffled order) of an array of size N, the task is to find the no of possible array's of the size N which can be made from these elements Examples: Input: arr[] = {5, 2, 3, 5} Output: 2 Explanation: 1st array can be : {2, 3} Its prefix array:{2, 5} Its suffix array:{5, 3} 2nd arr
15+ min read
Find Maximized difference between two elements for every index of given Arrays
Given two arrays A[] and B[] of the same length N. the task is to find a pair (X, Y) for two numbers Ai (number at i index of array A) and Bi(number at i index of array B) such that the value of |X-Y| is maximized for each index and the pair satisfies the following conditions: 1 ≤ X, Y ≤ Bigcd(X, Y) ≥ Ai Note: If there are multiple possible pairs f
6 min read
Count of Arrays of size N having absolute difference between adjacent elements at most 1
Given a positive integer M and an array arr[] of size N and a few integers are missing in the array represented as -1, the task is to find the count of distinct arrays after replacing all -1 with the elements over the range [1, M] such that the absolute difference between any pair of adjacent elements is at most 1. Examples: Input: arr[] = {2, -1,
15+ min read
Maximum absolute difference between sum of two contiguous sub-arrays
Given an array of integers, find two non-overlapping contiguous sub-arrays such that the absolute difference between the sum of two sub-arrays is maximum. Example: Input: [-2, -3, 4, -1, -2, 1, 5, -3] Output: 12 Two subarrays are [-2, -3] and [4, -1, -2, 1, 5] Input: [2, -1, -2, 1, -4, 2, 8] Output: 16 Two subarrays are [-1, -2, 1, -4] and [2, 8] E
15+ min read
Smallest Difference pair of values between two unsorted Arrays
Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {1, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {10, 5, 40} B[] = {50, 90, 80} Output : 10That is, the pair (40, 50)Brute For
11 min read
Find the compatibility difference between two arrays
Suppose there are two friends and now they want to test their friendship that how much compatible they are. Given the numbers n numbered from 1 ...n and they are asked to rank the numbers. The task is find the compatibility difference between them. Compatibility difference is the number of mis-matches in the relative ranking of the same movie given
5 min read
Practice Tags :