The Wayback Machine - https://web.archive.org/web/20240623174403/https://www.geeksforgeeks.org/dynamic-array-in-c/
Open In App

Dynamic Array in C

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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, dynamic arrays come into the picture.

A Dynamic Array is allocated memory at runtime and its size can be changed later in the program.

We can create a dynamic array in C by using the following methods:

  1. Using malloc() Function
  2. Using calloc() Function
  3. Resizing Array Using realloc() Function
  4. Using Variable Length Arrays(VLAs)
  5. Using Flexible Array Members

1. Dynamic Array Using malloc() Function

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It is defined inside <stdlib.h> header file.

Syntax:

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

We can use this function to create a dynamic array of any type by simply allocating a memory block of some size and then typecasting the returned void pointer to the pointer of the required type. 

Example:

ptr = (int*) malloc(100 * sizeof(int));

In the above example, we have created a dynamic array of type int and size 100 elements.

Note: It is to be noted that if malloc fails to allocate the required memory, it returns the NULL pointer. So, it is a good practice to check for NULL pointer to see if the memory is successfully allocated or not.

Example:

C




// C program to create dynamic array using malloc() function
  
#include <stdio.h>
#include <stdlib.h>
  
int main()
{
  
    // address of the block created hold by this pointer
    int* ptr;
    int size;
  
    // Size of the array
    printf("Enter size of elements:");
    scanf("%d", &size;);
  
    //  Memory allocates dynamically using malloc()
    ptr = (int*)malloc(size * sizeof(int));
  
    // Checking for memory allocation
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
    }
    else {
  
        // Memory allocated
        printf("Memory successfully allocated using "
               "malloc.\n");
  
        // Get the elements of the array
        for (int j = 0; j < size; ++j) {
            ptr[j] = j + 1;
        }
  
        // 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:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

2. Dynamic Array Using calloc() Function

The “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type and initialized each block with a default value of 0.

The process of creating a dynamic array using calloc() is similar to the malloc() method. The difference is that calloc() takes arguments instead of one as compared to malloc(). Here, we provide the size of each element and the number of elements required in the dynamic array. Also, each element in the array is initialized to zero.

Syntax:

ptr = (cast-type*)calloc(n, element-size);

Example:

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

In the above example, we have created a dynamic array of type float having five elements.

Let’s take another example to create a dynamic array using the calloc() method.

Example:

C




// C program to create dynamic array using calloc() function
  
#include <stdio.h>
#include <stdlib.h>
  
int main()
{
  
    // address of the block created hold by this pointer
    int* ptr;
    int size;
  
    // Size of the array
    printf("Enter size of elements:");
    scanf("%d", &size;);
  
    //  Memory allocates dynamically using calloc()
    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 "
               "malloc.\n");
  
        // Get the elements of the array
        for (int j = 0; j < size; ++j) {
            ptr[j] = j + 1;
        }
  
        // 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:6
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 

3. Dynamically Resizing Array Using realloc() Function

The “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.

Using this function we can create a new array or change the size of an already existing array.

Syntax:

ptr = realloc(ptr, newSize);

Let’s take an example to understand this properly.

Example:

C




// C program to resize dynamic array using realloc()
// function
  
#include <stdio.h>
#include <stdlib.h>
  
int main()
{
  
    // address of the block created hold by this pointer
    int* ptr;
    int size = 5;
  
  
    //  Memory allocates dynamically using calloc()
    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 + 1;
    }
  
    printf("The elements of the array are: ");
    for (int k = 0; k < size; ++k) {
        printf("%d, ", ptr[k]);
    }
  
    printf("\n");
  
    size = 10;
  
    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 + 10;
    }
  
    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: 1, 2, 3, 4, 5, 
Memory successfully re-allocated using realloc.
The new elements of the array are: 1, 2, 3, 4, 5, 15, 16, 17, 18, 19, 

To Know more about these above methods, please refer to the article – malloc, calloc,free in C

4. Variable Length Arrays(VLAs)

Variable length arrays or VLAs, are those arrays in which we can determine the size of the array at the run time. It allocates the memory in the stack and it’s based on the local scope level.

The size of a variable length array cannot be changed once it is defined and using variable length array as its found down sides as compared to above methods.

Example:

C




// 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: 5
Enter elements: 1 2 3 4 5
Elements of VLA of Given Size: 1 2 3 4 5

To know more about variable length arrays, please refer to the article –Variable Length Arrays in C/C++.

5. Flexible Array Members

The flexible array members are the array that is defined inside a structure without any dimension and their size is flexible. This feature was introduced in C99 standard.

We can control the size of a flexible member using malloc() function.

There are a few rules to follow in the case of flexible array members:

  • The array inside the structure should preferably be declared as the last member of the structure and its size is variable(can be changed at runtime).
  • The structure must contain at least one more named member in addition to the flexible array member.

Let’s take the following structure for example

struct student
{
  int len;
  int 
};

Now to allocate memory, we will use malloc() function as shown below.

struct student *s = malloc(sizeof(*s) + 5 * sizeof(int));

Example:

C




// 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 + 1;
    }
    for (int i = 0; i < 10; i++) {
        fam2->arr[i] = i + 10;
    }
  
    //  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:
1, 2, 3, 4, 5, 
Array of size 10:
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 

To know more about flexible array members, please refer to the article – Flexible Array Members Structure in C.

Dynamic Allocation of Two-Dimensional Array

We can also create a two-dimensional dynamic array in c.  These are the following different ways to create a 2D dynamic array.

  1. Using a single pointer and a 1D array with pointer arithmetic
  2. Using an array of pointers 
  3. Using a pointer to a pointer 
  4. Using a double-pointer and one malloc call 
  5. Using a pointer to Variable Length Array
  6. Using a pointer to the first row of VLA

To know more about the Dynamic Allocation of Two-Dimensional Arrays, refer to the article – How to dynamically allocate a 2D array in C?



Previous Article
Next Article

Similar Reads

How to Create a Dynamic 2D Array Inside a Class in C++?
A dynamic array is an array that can grow, resize itself, contains a dynamic table, which is mutable in nature, or an array list is randomly accessible, the variable-size list data structure that allows elements to be added or removed. Suppose we want to create a class for Graph. The class stores the adjacency matrix representation of the graph. Ex
3 min read
How to Create a Dynamic Array of Structs?
In C, we have dynamic arrays in which we can allocate an array of elements whose size is determined during runtime. In this article, we will learn how to create a dynamic array of structures in C. Create a Dynamic Array of Structs in CA dynamic array of structs in C combines dynamic arrays and structures to organize and store multiple pieces of rel
2 min read
How to Find Size of Dynamic Array in C?
In C, dynamic memory allocation allows us to manage memory resources during the execution of a program. It’s particularly useful when dealing with arrays where the size isn’t known at compile time. In this article, we will learn how to find the size of a dynamically allocated array in C. Find Size of a Dynamically Allocated Array in CWhen we dynami
2 min read
How to Create a Dynamic Array Inside a Structure?
In C, the structure can store the array data types as one of its members. In this article, we will learn how to create a dynamic array inside a structure in C. Creating a Dynamic Array Inside a Structure in CTo create a dynamic array inside a structure in C, define a structure that contains a pointer to the array type and a variable to store the si
2 min read
How to Create a Dynamic Array of Strings in C?
In C, dynamic arrays are essential for handling data structures whose size changes dynamically during the program's runtime. Strings are arrays of characters terminated by the null character '\0'. A dynamic array of strings will ensure to change it's size dynamically during the runtime of the program as per the user's needs. In this article, we wil
3 min read
How are variables scoped in C - Static or Dynamic?
In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack. For example, output for the below program is 0, i.e., the value returned by f() is not dependent on who is calling it. f() always returns the value of the global variable x
1 min read
C | Dynamic Memory Allocation | Question 1
The most appropriate matching for the following pairs (GATE CS 2000) X: m=malloc(5); m= NULL;        1: using dangling pointers Y: free(n); n-&gt;value=5;         2: using uninitialized pointers Z: char *p; *p = ’a’;           3. lost memory is: (A) X—1 Y—3 Z-2 (B) (X—2 Y—1 Z-3 (C) X—3 Y—2 Z-1 (D) X—3 Y—1 Z-2 Answer: (D) Explanation: X -&gt; A poin
1 min read
C | Dynamic Memory Allocation | Question 2
Consider the following three C functions : [PI] int * g (void) { int x= 10; return (&amp;x); } [P2] int * g (void) { int * px; *px= 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; } Which of the above three functions are likely to cause problems with pointers? (GATE 2001) (A) Only P3 (B) Only P1
1 min read
C | Dynamic Memory Allocation | Question 3
Output? C/C++ Code # include # include void fun(int *a) { a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(p); *p = 6; printf(\"%d",*p); return(0); } (A) May not work (B) Works and prints 6 Answer: (A)Explanation: The program is not valid. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer. This is
1 min read
C | Dynamic Memory Allocation | Question 8
Which of the following is/are true (A) calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has uninitialized data. (B) malloc() and memset() can be used to get the same effect as calloc(). (C) calloc() takes two arguments, but malloc takes only 1 argument. (D) Both malloc() and call
1 min read
Article Tags :
three90RightbarBannerImg