Dynamic Array In C - C Programming Tutorial
C Course / Programs / Dynamic Array In C

Dynamic Array In C

BLUF: Understanding Dynamic Array In C is a foundational part of learning C programming. This tutorial explains the core principles and syntax needed to implement this concept effectively.
Core Programming Principle: Dynamic Array In C

C provides direct access to memory and system resources. Learn how Dynamic Array In C leverages this power in the lesson below.

A dynamic array is an array that can be adjusted in size during execution. In contrast to fixed-size static arrays, whose dimensions are set at compile time, dynamic arrays offer the advantage of resizable dimensions. This feature provides increased flexibility and improved memory utilization by allowing the array size to adapt to the volume of stored data.

Dynamic arrays are created through pointers and memory allocation functions. In the C programming language, the primary memory allocation functions employed are malloc, calloc, and realloc. These functions facilitate the dynamic allocation and release of memory at execution time, essential for managing dynamic arrays effectively.

Advantages of Dynamic Arrays

There are several advantages to using dynamic arrays in C. Some of the main advantages are as follows:

  • One of the main advantages is that they allow for better memory management. With static arrays, the size of the array is fixed , which means that memory is allocated for the entire array at once. It can lead to wasted memory if the array is not fully utilized.
  • With dynamic arrays, memory is only allocated as needed, which can lead to more efficient memory usage.
  • Dynamic arrays also allow for greater flexibility.
  • It can be limiting, especially if the size of the array needs to change during runtime.
  • Dynamic arrays allow for the size of the array to be adjusted as needed, which can make programs more versatile and adaptable.
  • Disadvantages of Dynamic Arrays

While dynamic arrays have many advantages, they also have some disadvantages. Some of the main disadvantages are as follows:

  • One of the main disadvantages is that they can be more complex to implement than static arrays.
  • Dynamic arrays require the use of pointers and memory allocation functions , which can be more difficult to understand and use than the simple array syntax of static arrays.
  • Dynamic arrays can also be slower than static arrays. Because memory allocation and deallocation are involved, there is an overhead cost associated with using dynamic arrays. This overhead cost can make dynamic arrays slower than static arrays in some cases.
  • Creating Dynamic Arrays in C

To establish a resizable array in C, we need to employ memory allocation functions to reserve memory for the array. The prevalent memory allocation functions in C include malloc, calloc, and realloc. Below is a sample demonstrating the creation of a dynamic array using malloc:

Example

int *arr;
int size = 10;
arr = (int*) malloc(size * sizeof(int));

Explanation:

In this instance, we define a pointer to an array of integers named arr. Additionally, we define an integer variable named size, which signifies the desired size of the array. Following this, we employ the malloc function to reserve memory for the array. The malloc function requires the size of the array in bytes as its parameter, so we calculate the total size in bytes by multiplying the array's size by the size of an integer (typically 4 bytes on most systems).

Manipulating Dynamic Arrays in C

Once a dynamic array is established in C, it can be manipulated similarly to a standard array. Accessing specific elements of the array is achieved through array syntax:

Example

arr[0] = 5;

In this instance, we assign the value 5 to the initial element of the array.

We can also use loops to iterate over the array:

Example

for (int i = 0; i< size; i++) {
arr[i] = i * 2;
}

In this instance, a for loop is employed to assign a value to each item in the array that equals double its position.

To adjust the size of a dynamic array in C, realloc function comes in handy. It requires two parameters: a reference to the initial memory block and the updated size of the memory block. Below demonstrates how realloc can be employed to resize a dynamic array:

Example

int new_size = 20;
arr = (int*) realloc(arr, new_size * sizeof(int));

In this instance, a fresh integer variable named new_size is defined to indicate the updated array size. Subsequently, the array is resized using the realloc function. This function requires the original memory block pointer (in this scenario, arr) and the new memory block size (in bytes). The total size in bytes is calculated by multiplying the new array size by the size of an integer.

It's essential to emphasize that when resizing a dynamic array with realloc, the data already present in the array will be retained. In cases where the new array size exceeds the original, the additional elements will be uninitialized.

To release the memory occupied by a dynamic array in C, we can employ the free function. This function requires a pointer to the memory chunk that was reserved using malloc, calloc, or realloc. Below is a demonstration of freeing the memory utilized by a dynamic array:

Example

free(arr);

In this instance, we employ the free function to release the memory allocated for the dynamic array named arr. It is crucial to emphasize that after deallocating the memory associated with a dynamic array, accessing its elements should be avoided.

Some more examples of using dynamic arrays in C:

Adding Elements to a Dynamic Array:

One of the primary advantages of utilizing a dynamic array is the capability to append elements to the array as required. Below is a demonstration of adding an element to a dynamic array:

Example

#include <stdio.h>
#include <stdlib.h>
int main() {
    int size = 5;
    int *arr = (int*) malloc(size * sizeof(int));
    int i;
for(i = 0; i< size; i++) {
arr[i] = i;
    }
    // Add a new element to the array
    size++;
arr = (int*) realloc(arr, size * sizeof(int));
arr[size-1] = i;
for(i = 0; i< size; i++) {
printf("%d ", arr[i]);
    }
    free(arr);
    return 0;
}

Output:

Output

0 1 2 3 4 5

Explanation:

In this instance, we initiate a dynamic array named arr with a capacity of 5 by employing the malloc function. Subsequently, we assign each element in the array to its corresponding index through an iterative loop. To introduce a fresh element to the array, we augment the array's size by one and adjust the array's dimensions using the realloc function. The last element in the array is then assigned the current value of i. Ultimately, we display the array's contents, followed by deallocating the memory allocated for the array.

Resizing a Dynamic Array

One more benefit of utilizing a dynamic array is the capability to adjust the array size as required. Below is a demonstration of resizing a dynamic array:

Example

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

int main() {
    int size = 5;
    int *arr = (int*) malloc(size * sizeof(int));
    int i;

for(i = 0; i< size; i++) {
arr[i] = i;
    }

    // Resize the array
    size = 10;
arr = (int*) realloc(arr, size * sizeof(int));

for(i = 5; i< size; i++) {
arr[i] = i;
    }

for(i = 0; i< size; i++) {
printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}

Output:

Output

0 1 2 3 4 5 6 7 8 9

Explanation:

In this instance, we initially establish a dynamic array named arr with a capacity of 5 using the malloc method. Subsequently, we iterate through a for loop to assign each element in the array to its corresponding index. To adjust the array size, we update the size to 10 and utilize the realloc function for resizing. Following this, another for loop is employed to assign values to the new elements within the array. Ultimately, we display the array's contents and release the memory allocated for the array.

Conclusion

Dynamic arrays represent a robust data structure in programming, enabling the generation and modification of arrays with flexible sizes at runtime. In the C programming language, dynamic arrays are constructed through pointers and memory allocation functions, serving as a beneficial resource for enhancing memory utilization and developing streamlined programs.

While dynamic arrays offer numerous benefits, they come with certain drawbacks as well. Implementing dynamic arrays can be more intricate compared to static arrays and may result in slower performance under certain circumstances. Nonetheless, the adaptability and effectiveness of dynamic arrays render them an invaluable resource for a wide range of programming assignments.

When working with dynamic arrays in C, it is essential to utilize memory allocation functions for allocating and releasing memory as needed during program execution. The primary memory allocation functions frequently employed in C include malloc, calloc, and realloc. Effective memory management is crucial to prevent memory leaks and address other memory-related concerns that may arise when dealing with dynamic arrays.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience