The Wayback Machine - https://web.archive.org/web/20240919142433/https://www.geeksforgeeks.org/dynamically-growing-array-in-c/
Open In App

Dynamically Growing Array in C

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

Prerequisite: Dynamic Memory Allocation in C

A Dynamically Growing Array is a type of dynamic array, which can automatically grow in size to store data.

The C language only has static arrays whose size should be known at compile time and cannot be changed after declaration. This leads to problems like running out of space or not using the allocated space leading to memory wastage. Programming languages like C++, Python, Java, etc already come equipped with containers for which the programmer doesn’t have to worry about the size.

So, our objective is to create a dynamic array that should automatically be able to manage its own size depending on the requirement.

In this article, we will create a Dynamically Growing Array using pointers and dynamic memory allocation.

Basic Principle

The basic principle of the Dynamically Growing Array is the dynamic memory allocation concept in C which allow the users to allocate memory at runtime and also change the allocated size afterward.

Working

Dynamically Growing Array in C

Dynamically Growing Array in C

  • The initial size of the newly created array would be small.
  • Different functions would provide all the basic operations that a conventional array provides.
  • When the array runs out of space, the capacity would be doubled by using realloc() to reallocate the array.
  • The reason for doubling the capacity instead of increasing it one by one on demand is that the calls to realloc() are expensive calls. If we call realloc() again and again, it may increase the insertion time of the element to O(n) negating the advantages of using an array. Doubling the size has amortized constant time complexity for insertion operation.
  • After we have done our task involving the array, we can also clear the memory using free().

Following is the C Program for Dynamically Growing Array:

C




// C program to demonstrate the 
// dynamically growing array
#include <stdio.h>
#include <stdlib.h>
  
#define INITIAL_SIZE 8
  
// base structure
typedef struct {
    size_t size;
    size_t capacity;
    int* array;
}dynamic_array;
  
// function prototypes
//  array container functions
void arrayInit(dynamic_array** arr_ptr);
void freeArray(dynamic_array* container);
  
// Basic Operation functions
void insertItem(dynamic_array* container, int item);
void updateItem(dynamic_array* container, int i, int item);
int getItem(dynamic_array* container, int i);
void deleteItem(dynamic_array* container, int item);
void printArray(dynamic_array* container);
  
  
// driver code
int main()
{
    dynamic_array* arr;
    arrayInit(&arr;);
      
    for (int i = 0; i < 6; i++) {
        insertItem(arr, i + 11);
    }
    printArray(arr);
    printf("%d\n", getItem(arr, 3));
    deleteItem(arr, 3);
    printArray(arr);
  
    for (int i = 0; i < 5; i++) {
        insertItem(arr, i + 17);
    }
  
    printArray(arr);
  
    freeArray(arr);
    int var;
    return 0;
}
  
//------Function Definitions------
// Array initialization
void arrayInit(dynamic_array** arr_ptr)
{
    dynamic_array *container;
    container = (dynamic_array*)malloc(sizeof(dynamic_array));
    if(!container) {
        printf("Memory Allocation Failed\n");
        exit(0);
    }
  
    container->size = 0;
    container->capacity = INITIAL_SIZE;
    container->array = (int *)malloc(INITIAL_SIZE * sizeof(int));
    if (!container->array){
        printf("Memory Allocation Failed\n");
        exit(0);
    }
  
    *arr_ptr = container;
}
  
//  Insertion Operation
void insertItem(dynamic_array* container, int item)
{
    if (container->size == container->capacity) {
        int *temp = container->array;
        container->capacity <<= 1;
        container->array = realloc(container->array, container->capacity * sizeof(int));
        if(!container->array) {
            printf("Out of Memory\n");
            container->array = temp;
            return;
        }
    }
    container->array[container->size++] = item;
}
  
// Retrieve Item at Particular Index
int getItem(dynamic_array* container, int index)
{
    if(index >= container->size) {
        printf("Index Out of Bounds\n");
        return -1;
    }
    return container->array[index];
}
  
// Update Operation
void updateItem(dynamic_array* container, int index, int item)
{
    if (index >= container->size) {
        printf("Index Out of Bounds\n");
        return;
    }
    container->array[index] = item;
}
  
// Delete Item from Particular Index
void deleteItem(dynamic_array* container, int index)
{
    if(index >= container->size) {
        printf("Index Out of Bounds\n");
        return;
    }
  
    for (int i = index; i < container->size; i++) {
        container->array[i] = container->array[i + 1];
    }
    container->size--;
}
  
// Array Traversal
void printArray(dynamic_array* container)
{
    printf("Array elements: ");
    for (int i = 0; i < container->size; i++) {
        printf("%d ", container->array[i]);
    }
    printf("\nSize: ");
    printf("%lu", container->size);
    printf("\nCapacity: ");
    printf("%lu\n", container->capacity);
}
  
// Freeing the memory allocated to the array
void freeArray(dynamic_array* container)
{
    free(container->array);
    free(container);
}


Output

Array elements: 11 12 13 14 15 16 
Size: 6
Capacity: 8
14
Array elements: 11 12 13 15 16 
Size: 5
Capacity: 8
Array elements: 11 12 13 15 16 17 18 19 20 21 
Size: 10
Capacity: 16

As we can see that our program for dynamically growing array is working as desired. Let’s understand the components of this program one by one.

Components of Dynamically Growing Array

  1. dynamic_array: The base structure for the dynamically growing array.
  2. arrayInit(): This function is to initialize the array.
  3. deleteArr(): This function is for freeing the memory once we are done with the array.

1. dynamic_array

It is the name given to the structure type which serves as the container for our dynamically growing array. It contains 3 members:

  • size: Counter to track the memory used.
  • capacity: Counter to track the maximum capacity of the array.
  • array: Pointer pointing to the actual storage location. (For this program, we will be using an array of type int)

Code:

typedef struct {
    size_t size;
    size_t capacity;
    int* array;
} dynamic_array;

2. arrayInit()

This function initializes the dynamic array with the default initial size which is set to 8. This function takes the address of the double-pointer to the dynamic_array pointer as an argument.

Code:

void arrayInit(dynamic_array** arr_ptr)
{
    dynamic_array *container;
    container = (dynamic_array*)malloc(sizeof(dynamic_array));
    if(!container) {
        printf("Memory Allocation Failed\n");
        exit(0);
    }

    container->size = 0;
    container->capacity = INITIAL_SIZE;
    container->array = (int *)malloc(INITIAL_SIZE * sizeof(int));
    if (!container->array){
        printf("Memory Allocation Failed\n");
        exit(0);
    }

    *arr_ptr = container;
}

3. freeArray()

This function frees the memory allocated to the dynamically growing array. This function should be called after we are done using the array.

Code:

void freeArray(dynamic_array* container)
{
    free(container->array);
    free(container);
}

Rest components are the functions providing basic array operations for our Dynamically Growing Array. They are discussed below:

Basic Operations

There are 5 functions that provide the basic operations of an array which are as follows:

  1. insertItem(): For inserting an element at the end of the array
  2. getItem(): For retrieving the element at the given index
  3. updateItem(): For updating an element at that given index of the array
  4. printItem(): For printing all the elements of the array
  5. deleteItem(): For deleting an element of the array at the given index

1. insertItem() 

The insertItem() function provides the insertion operation using which we can insert elements in the array. When there is space left for the elements, the insertItem() function will put elements in the array without changing size.

But when the space is completely filled, the space allocated to the array will be doubled using realloc() function and then the insertion will be done.

Code:

void insertItem(dynamic_array* container, int item)
{
    if (container->size == container->capacity) {
        int *temp = container->array;
        container->capacity <<= 1;
        container->array = realloc(container->array, container->capacity * sizeof(int));
        if(!container->array) {
            printf("Out of Memory\n");
            container->array = temp;
            return;
        }
    }
    container->array[container->size++] = item;
}

2. getItem()

This function returns the integer value present at the given index. It takes two arguments – container address and index.

Code:

int getItem(dynamic_array* container, int index)
{
    if(index > container->size) {
        printf("Index Out of Bounds\n");
        return -1;
    }
    return container->array[index];
}

3. updateItem()

The updateItem() function facilitates us to update the element present at a particular index. This function take 3 arguments – container address, index, and updated_item.

Code:

void updateItem(dynamic_array* container, int index, int item)
{
    if (index > container->size) {
        printf("Index Out of Bounds\n");
        return;
    }
    container->array[index] = item;
}

4. printItem()

This function traverses the array and prints all the elements. Apart from that, it also prints the current size and capacity of the array.

Code:

void printArray(dynamic_array* container)
{
    printf("Array elements: ");
    for (int i = 0; i < container->size; i++) {
        printf("%d ", container->array[i]);
    }
    printf("\nSize: ");
    printf("%ld", container->size);
    printf("\nCapacity: ");
    printf("%ld\n", container->capacity);
}

5. deleteItem()

The deleteItem() function provides the deletion operation using which we can remove the element at any particular index.

Code:

void deleteItem(dynamic_array* container, int index)
{
    if(index > container->size) {
        printf("Index Out of Bounds\n");
        return;
    }

    for (int i = index; i < container->size; i++) {
        container->array[i] = container->array[i + 1];
    }
    container->size--;
}


Previous Article
Next Article

Similar Reads

How to dynamically allocate a 2D array in C?
Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).In the following examples, we have considered 'r' as number of rows, 'c' as number of columns and we created a 2D array with r = 3, c = 4 and the following values 1 2 3 4 5 6 7 8 9 10 11 12 1) Using a single pointer and a 1D array with pointer arithme
5 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read
What’s difference between “array” and “&amp;array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&amp;array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Jagged Array or Array of Arrays in C with Examples
Prerequisite: Arrays in C Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}, {5} }; Below are the methods to implement the j
3 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element
5 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include&lt;stdio.h&gt; int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(&quot;%p\n&quot;, ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the &amp; operator array is an alias for &amp;array[0
1 min read
Properties of Array in C
An array in C is a fixed-size homogeneous collection of elements stored at a contiguous memory location. It is a derived data type in C that can store elements of different data types such as int, char, struct, etc. It is one of the most popular data types widely used by programmers to solve different problems not only in C but also in other langua
8 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
Sort an array using socket programming in C
Given an array of unsorted positive integer, sort the given array using the Socket programming . Examples: Input : 4 5 6 1 8 2 7 9 3 0 Output :0 1 2 3 4 5 6 7 8 9 Input : 9 8 1 4 0 Output : 0 1 4 8 9 Compile these files using gcc command (gcc client.c -o client and gcc server.c -o server). Run the program using ./server and ./client (Please note :
3 min read
4 Dimensional Array in C/C++
Prerequisite :Array in C/C++, More on array A four-dimensional (4D) array is an array of array of arrays of arrays or in other words 4D array is a array of 3D array. More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding arrays. Declaration of a Multidimensional Array in C: Syntax: data_
3 min read
Input an integer array without spaces in C
How to input a large number (a number that cannot be stored even in long long int) without spaces? We need this large number in an integer array such that every array element stores a single digit. Input : 10000000000000000000000000000000000000000000000 We need to read it in an arr[] = {1, 0, 0...., 0} In C scanf(), we can specify count of digits t
2 min read
Different ways to Initialize all members of an array to the same value in C
An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it. int num[100]; How to declare an array in C? Data_type array_name[size_of_array]; For example, float num[10]; Below are some of the different ways in which all elements of an array
3 min read
Difference between Structure and Array in C
Array in C An array is collection of items stored at contiguous memory locations. Structure in C A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. Difference between Structure and Array ARRAYSTRUCTUREArray refers to a collection consistin
2 min read
C program to Insert an element in an Array
Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C. Follow the below steps to solve the problem: First get the element to be inserted,
2 min read
Count ways to reach the Nth stair using any step from the given array
Given N stairs and a person standing at the bottom wants to reach the top. He could climb any number of steps from the given array arr[] of positive integers. The task is to find the count of all possible ways to reach the top. Examples: Input: arr[] = {1, 3, 5}, N = 5 Output: 5 (0 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5), (0 -&gt; 1 -&gt; 2 -&gt;
10 min read
Duplicates Removal in Array using BST
Given an array arr[] of integers, the task is to remove duplicates from the given array. Examples: Input: arr[] = {1, 2, 3, 2, 5, 4, 4} Output: arr[] = {1, 2, 3, 4, 5} Input: arr[] = {127, 234, 127, 654, 355, 789, 355, 355, 999, 654} Output: arr[] = {127, 234, 355, 654, 789, 999} The duplicates in the array can be removed using Binary Search Tree.
7 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
Reverse an array in groups of given size | Set 3 (Single traversal)
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3. Output: [3, 2, 1, 6, 5, 4, 9, 8, 7, 10]Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 5. Output: [5, 4, 3, 2, 1, 7, 6] Approach: We will use two pointers technique to solve this problem.First, we will initialize our 1st
6 min read
Difference between Array and Union in C
1. Array in C : An array is collection of similar data items accessed by a common name stored at continuous memory locations. The elements of an array can be accessed using indices. They can be used to store primitive data types such as int, float, double, char, etc. but all elements have to be of the same data type. Below is the picturesque repres
2 min read
How to Get Value of Multidimensional Array in C?
Prerequisite: Array in C An array is a type of data structure where we can store multiple elements of similar data types. A multidimensional array can be termed an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. Declaration of Array Declaration or Initialisation of an arra
8 min read
How to Declare and Initialize an Array of Pointers to a Structure in C?
Prerequisite: Structure in CArray in C In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create
8 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
Changing Array Inside Function in C
When declaring an array the array name is always called the pointer because in an array name the address of the 0th block(base address) is stored. To change an array in the function we have to pass an array in the function. For this, an array_name is passed to the function in the form of an actual argument. So an address of the 0th block pass to th
2 min read
How to Check if Empty Array in C?
Prerequisite: Array in C The array is a type of Data-structure that can store homogeneous data-type elements. The size of the array is fixed. Syntax: int arr[N]; here, the data type of the array is an integer, the name of an array is arr, and the size of the array is N. Example: C/C++ Code // C Program to declare an // array and check it's size #in
3 min read
Why can't a const variable be used to define an Array's initial size in C?
What is an array? An array is a collection of items of the same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index
3 min read
How to Empty a Char Array in C?
Prerequisite: Char Array in C Char arrays are used for storing multiple character elements in a continuous memory allocated. In a few questions, we have the necessity to empty the char array but You can’t clear a char array by setting the individual members to some value indicating that they don’t contain anything. So, we need some other methods to
4 min read
Dynamic Array in C
Array in C is static in nature, so its size should be known at compile time and we can't change the size of the array after its declaration. Due to this, we may encounter situations where our array doesn't have enough space left for required elements or we allotted more than the required memory leading to memory wastage. To solve this problem, dyna
9 min read
Article Tags :