Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Dynamic Array in C

Last Updated on June 19, 2023 by Mayank Dham

This blog aims to provide an in-depth understanding of dynamic arrays in C, which are also referred to as variable-sized arrays. We will delve into different methods of creating dynamic arrays, explore their usage, and examine the scenarios where they are most applicable. Initially, we will establish a foundational understanding of fixed-length arrays, highlighting their limitations in certain situations and the necessity for dynamic arrays. Lastly, we will analyze the pros and cons of variable-sized arrays or dynamic arrays in the C programming language.

Fixed Length Arrays

Fixed length arrays, as their name implies, have a predetermined size during compilation, and this size cannot be altered during program execution. We can only define their size while writing the code, and thereafter, it remains constant. However, this approach is often suboptimal, as many situations require arrays of varying sizes. Although we can create an array with the largest feasible size, it would result in unnecessary memory waste. Variable Length Arrays (VLAs) offer a solution by allowing arrays to have sizes determined at runtime, accommodating the need for dynamic sizing.

Variable Length Array in C

Variable length arrays, also known as dynamic arrays, in C have their size determined at runtime (although the size cannot be modified after initialization). These arrays were first introduced in the C99 standard but became an optional feature in subsequent versions. Similar to normal arrays, dynamic arrays allocated on the stack are released when they go out of scope. In C++, we can also create dynamic arrays using similar techniques as in C, but there are additional methods available for creating dynamic arrays in C++.

Introduction to Dynamic Array in C

Not as many higher level languages like python and javascript provide inbuilt dynamic arrays but dynamic array in c is not an inbuilt function but c provides some features or methods to use dynamic array in c. These are the arrays that are resizable and can be accessed randomly. Dynamic array in c or dynamic array in CPP can be initialized by any size and that size can be changed further in the code. Dynamic array in c works on the heap whereas variable length array works on the stack.
Variable Length array is different from a dynamic array in c. Some differences among them are:

  • Allocation: The dynamic array in c is allocated on the heap whereas the variable length array in c is allocated on the stack so they work faster compared to the dynamic array in c.
  • Scope: Dynamic array in c or dynamic array in CPP does not bound by scope so can be used anywhere in the program until the memory is called using the free() function whereas the variable length array behaves as same as the normal array and is bounded by the scope.
  • Performance: Variable length arrays are comparatively faster than dynamic arrays in c as we have to allocate and deallocate memory manually in the dynamic array in c or in the dynamic array in CPP.

Different Methods to Create Dynamic Array in C

There are various methods to create a dynamic array in c. Here we will see 5 methods to create a dynamic array in c++ or a dynamic array in c as the method we will use in c will also be applicable in the case of c++.

We will discuss five methods to create a dynamic array in c and these are mentioned below:

  • Using the malloc() Function.
  • Using calloc() Function.
  • Using Variable Length Array
  • Resizing array using realloc() function
  • Using flexible array members.

1. Dynamic Array in C using malloc() function

In C, a single big block of memory with the requested size is dynamically allocated using the "malloc" or "memory allocation" technique. It returns a void pointer that may be cast into any other pointer type. It is included in the header file . The syntax for using the malloc() function to create a dynamic array in c is shown below:

ptr = (cast-type*) malloc(byte-size);

Example of creating a dynamic array in C using malloc() function
In this section we will use malloc function to create a dynamic array in c and will discuss the code and output of the corresponding code.

#include 
#include 

int main()
{

    int* ptr;
    int size;
// we will take the size of the array
    printf("Enter size of elements:");
    scanf("%d", &size);

// dynamically allocate memory using malloc() method.
ptr = (int*)malloc(size * sizeof(int));

    if (ptr == NULL) {
        printf("Memory not allocated.\n");
    }
    else {

        printf("Memory successfully allocated using "
            "malloc.\n");

        // Get the elements of the array
        for (int j = 0; j < size; ++j) {
            ptr[j] = j + 10;
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (int k = 0; k < size; ++k) {
            printf("%d, ", ptr[k]);
        }
    }

    return 0;
}

Output

Enter size of elements: Memory successfully allocated using malloc.
The elements of the array are: 10, 11, 12, 13, 14, 15,

Explanation of the above Code
In the above code we have asked the user to give the size of the array and then we are allocating the elements to the array. After setting the value of the elements of the dynamic array in c we are printing those values.

2. Dynamic Array using calloc() function.

When dynamically allocating the specified number of memory blocks of the specified type in C, the "calloc" or "contiguous allocation" technique is used. Each block is initialized with a default value of 0, and the method is used to allocate memory blocks in this way.
Using the calloc() function is comparable to using the malloc() technique to allocate memory for a dynamic array in c. When compared to malloc, calloc() differs in that it accepts multiple parameters (). The size of each element and the necessary number of elements for the dynamic array in c are given below. The array’s elements are all initialized to 0 as well.

ptr = (int*) calloc(5, sizeof(float));

Example of creating a dynamic array in C using calloc function
In this section we will use calloc function to create a dynamic array in c and will discuss the code and output of the corresponding code.

#include <stdio.h>
#include <stdlib.h>

int main()
{

    // address of the block created hold by this pointer
    int* ptr;
    int size;

// taking the size as input from the user 
printf("Enter size of elements:");
    scanf("%d", &size);

// allocating the memory using calloc dynamically
ptr = (int*)calloc(size, sizeof(int));

    // Checking for memory allocation
    if (ptr == NULL) {
        printf("Memory not allocated .\n");
    }
    else {

        // Memory allocated
        printf("Memory successfully allocated using "
            "calloc.\n");

        // Get the elements of the array
        for (int j = 0; j < size; ++j) {
            ptr[j] = j + 10;
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (int k = 0; k < size; ++k) {
            printf("%d, ", ptr[k]);
        }
    }

    return 0;
}

Output

Enter size of elements: Memory successfully allocated using calloc.
The elements of the array are: 10, 11, 12, 13, 14, 15,

Explanation of the above code
In the above code we have asked the user to give the size of the array and then we are allocating the elements to the array. After setting the value of the elements of the dynamic array in c we are printing those values.

3. Dynamically resizing Dynamic Array in C using realloc() function.

To dynamically change the memory allocation of previously allocated memory in C, use the "realloc" or "re-allocation" technique. In other words, if the memory originally allocated with malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. After re-allocating memory, the current value is kept, and new blocks are initially started with trash.

ptr = realloc(ptr, newSize);

Example of resizing a dynamic array in C using realloc() function
In this example we will see how we can change the size of a dynamic array in c after allocating all the elements to it and then after changing the size again allocating new values to the elements.

Code Implementation:

#include 
#include 

int main()
{

    // address of the block created hold by this pointer
    int* ptr;
    int size = 5;


    ptr = (int*)calloc(size, sizeof(int));

    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
        printf("Memory successfully allocated using "
            "calloc.\n");
    }

    // inserting elements
    for (int j = 0; j < size; ++j) {
        ptr[j] = j + 10;
    }

    printf("The elements of the array are: ");
    for (int k = 0; k < size; ++k) {
        printf("%d, ", ptr[k]);
    }

    printf("\n");

    size = 15;

    int *temp = ptr;

    // using realloc
    ptr = realloc(ptr, size * sizeof(int));
    if (!ptr) {
        printf("Memory Re-allocation failed.");
        ptr = temp;
    }
    else {
        printf("Memory successfully re-allocated using "
            "realloc.\n");
    }

    // inserting new elements
    for (int j = 5; j < size; ++j) {
        ptr[j] = j + 100;
    }

    printf("The new elements of the array are: ");
    for (int k = 0; k < size; ++k) {
        printf("%d, ", ptr[k]);
    }
    return 0;
}

Output

Memory successfully allocated using calloc.
The elements of the array are: 10, 11, 12, 13, 14, 
Memory successfully re-allocated using realloc.
The new elements of the array are: 10, 11, 12, 13, 14, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,

Explanation of the above code
In the above code we have first allocated the size of the array by asking the user and then assigning the values using the corresponding code we have written after that we changed the size of the dynamic array in c and then set the new values of the newly added spaces afterward and then print the answer.

4. Variable Length Arrays

Variable length arrays, also known as VLAs, are those arrays where the size of the array may be changed at runtime. It bases the memory allocation for the stack on the local scope level.
When opposed to the methods above, a variable length array has the disadvantage that once defined, its size cannot be modified.

Example of Variable Length Arrays
In this section, we will look at the example of variable size arrays and how to use them to create a dynamic array in c.

Code Implementation:

// C program to demonstrate the use of VLAs
#include <stdio.h>

int main()
{

    int n;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    
    int arr[n];

    printf("Enter elements: ");

    for (int i = 0; i < n; ++i) {

        scanf("%d", &arr[i]);
    }
    
    printf("Elements of VLA of Given Size: ");
    for (int i = 0; i < n; ++i) {

        printf("%d ", arr[i]);
    }

    return 0;
}

Output

Enter the size of the array: Enter elements: Elements of VLA of Given Size: 5 7 9 11 23 41

Explanation of the above code
In the above example we have asked the user to give the size of the dynamic array in c and after that, we asked the user to give the elements of the array and then we printed those elements.

5. Flexible Array Members

The array that is defined inside a structure without any dimensions and whose size is flexible is known as a flexible array member. The C99 standard first included this functionality.
With the help of the malloc() method, we may regulate the size of a flexible member.
Preferably, the array inside the structure should be stated as its final member, and its size is changeable (can be changed at runtime).
In addition to the flexible array member, the structure must include at least one more named member.

Example of Flexible Array Members
Here we will see the example of flexible array members with proper code, and output followed by their explanation.

// C program to demonstrate the use of Flexible Array Member
#include <stdio.h>
#include <stdlib.h>

// defining struct
typedef struct {
    int len;
    int arr[];
} fam;

int main()
{
    // creating an array member of size 5
    fam* fam1
        = (fam*)malloc(sizeof(fam*) + 5 * sizeof(int));

    // creating an array mebmer of size 10
    fam* fam2
        = (fam*)malloc(sizeof(fam*) + 10 * sizeof(int));
    
    // inserting elements
    for (int i = 0; i < 5; i++) {
        fam1->arr[i] = i + 10;
    }
    for (int i = 0; i < 10; i++) {
        fam2->arr[i] = i + 100;
    }

    // printing elements
    printf("Array of Size 5:\n");
    for (int i = 0; i < 5; i++) {
        printf("%d, ", fam1->arr[i]);
    }
    printf("\n");

    printf("Array of size 10:\n");
    for (int i = 0; i < 10; i++) {
        printf("%d, ", fam2->arr[i]);
    }
    return 0;
}

Output

Array of Size 5:
10, 11, 12, 13, 14, 
Array of size 10:
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,

Explanation of the above code
In the above example we have created two arrays of size 5 and 10 respectively and then we have assigned the values to the elements of the value after that we have printed both the arrays to show that the assigned values are assigned properly to the elements.

Advantages of a Dynamic Array in C

  • Variable Size: Dynamic arrays allow for the allocation of memory at runtime, enabling the size of the array to be determined based on program logic or user input. This flexibility allows for efficient memory usage and better utilization of system resources.
  • Dynamic Memory Allocation: With dynamic arrays, memory can be allocated and deallocated as needed using functions like malloc(), calloc(), and realloc(). This allows for efficient memory management and reduces the risk of memory wastage.
  • Adaptability: Dynamic arrays can be resized during program execution, accommodating changing requirements or data sizes. This adaptability is particularly useful when dealing with input of unknown or varying lengths.
  • Reduced Memory Footprint: Unlike fixed-size arrays, dynamic arrays only consume memory that is required for the current size of the array. This leads to reduced memory footprint and efficient memory utilization.
  • Data Structures: Dynamic arrays form the foundation for various dynamic data structures such as linked lists, stacks, queues, and graphs. They enable the creation of more complex and flexible data structures that can grow or shrink based on the program’s needs.
  • Accessibility: Dynamic arrays provide direct access to elements using indexing, making it easy to read, modify, or traverse elements within the array.
  • Versatility: Dynamic arrays can be used in a wide range of applications, including file handling, sorting algorithms, database operations, and dynamic data processing.

Disadvantages of a Dynamic Array in C

  1. They can lead to fragmentation of memory if elements are frequently added and removed, which can decrease performance.
  2. They require additional memory overhead for memory management and bookkeeping.
  3. They can be less efficient in terms of time complexity for certain operations such as insertion and deletion, as these operations may require moving elements around in memory.
  4. They can be less efficient in terms of cache performance when compared to static arrays, due to the potential for cache misses when elements are spread out in memory.
  5. They are not thread-safe, meaning they can’t be accessed by multiple threads simultaneously.

Conclusion
Dynamic arrays in C provide flexibility and adaptability by allowing the allocation of memory at runtime. They offer advantages such as variable size, dynamic memory allocation, reduced memory footprint, and support for various data structures. However, proper memory management is essential to avoid issues like memory leaks or accessing out-of-bounds memory.

FAQs related to Dynamic Array in C:

Q1. Can the size of a dynamic array be changed after initialization?
No, the size of a dynamic array cannot be changed after initialization. The initial size is determined during runtime, and it remains fixed unless the array is deallocated and reallocated with a different size.

Q2. How do we allocate memory for a dynamic array in C?
Memory for a dynamic array in C can be allocated using functions like malloc(), calloc(), or realloc(). These functions allow you to specify the desired size in bytes and return a pointer to the allocated memory.

Q3. How do we deallocate memory for a dynamic array in C?
To deallocate memory for a dynamic array in C, the free() function is used. It releases the memory previously allocated by malloc(), calloc(), or realloc(). Failing to deallocate memory can result in memory leaks.

Q4. Can dynamic arrays cause memory fragmentation?
Yes, dynamic arrays can contribute to memory fragmentation. If memory is allocated and deallocated frequently in a non-contiguous manner, it can lead to fragmented memory blocks. This can reduce overall memory efficiency.

Q5. Are dynamic arrays automatically released from memory when they go out of scope?
No, dynamic arrays are not automatically released from memory when they go out of scope. It is the programmer’s responsibility to deallocate the memory using appropriate functions like free() to avoid memory leaks.

Q6. Can dynamic arrays be resized during program execution?
Yes, dynamic arrays can be resized during program execution using the realloc() function. It allows you to change the size of the allocated memory block, either expanding or shrinking the array as needed.

Q7. Can dynamic arrays be used in multi-dimensional arrays?
Yes, dynamic arrays can be used to create multi-dimensional arrays in C. By allocating memory for each dimension dynamically, you can create flexible multi-dimensional arrays of varying sizes.

Leave a Reply

Your email address will not be published. Required fields are marked *