How to change array size dynamically in C++

This tutorial focuses on the method to dynamically allocate memory and change array size according to the user input. This is a very useful method used in programming as it ensures efficient memory usage.

You come across such situations multiple times while programming where the size of the array depends on what the user enters at the time of execution. This technique makes the program flexible to act as per the requirement at runtime without any changes in the code. Using this technique will certainly be highly beneficial for programmers out there to write a clean and efficient code. I have provided step wise information later in the post. Feel free to leave a comment below.

C++ program to change array size dynamically

We will go through each step individually.

1. Declaring Variables

Code :

int *array_pointer;
int total_user_entries = 0;
int loop_count = 0;
int temporary[50];
int flag = 0;

 

array_pointer : Integer pointer is used to store pointer to the array we want to store user input in.
total_user_entries : Integer variable used to store total number of entries accepted from user. (initialized to zero)
loop_count : Integer variable used to count loop iterations. (initialized to zero)
temporary : Integer variable used to to temporarily store array values.
flag : used to check input termination condition.

 

2. Accept array data entries from user and store it in temporary variable array.

Code :

cout<<"\nEnter item entries: \n(Enter -1 to terminate input)\n";

while(flag == 0){

        cout << "\nEnter item " << loop_count+1 << ": ";
        cin >> temporary[loop_count];                       

        if(temporary[loop_count] == -1)
            flag = 1;

        loop_count++;

    }

total_user_entries = loop_count - 1;

 

We use a ‘while()’ loop to accept data from user. This array data is stored in temporary variable.
loop_count : variable is used to count the iterations and store data in temporary locations.
‘if()’ condition is used to check the input entered at every iteration and match with value ‘-1’. If the condition is met, the input loop is terminated using break; statement.

total_user_entries : total entries are counted according to loop_count. (1 less than loop count as ‘-1’ is used for termination and is not a data item)

( Note: “\n” is used to print text on a new line for better presentation. You can skip that line if you want. )

Output :

Enter item entries:
(Enter -1 to terminate input)

Enter item 1: 23 

Enter item 2: 56

Enter item 3: -1

 

3. Using ‘new‘ operator to allocate memory for array

What is a ‘new’ operator?
A new operator allocates memory for an object or array of objects of mentioned data type from the free storage. It returns a suitably typed and nonzero pointer to the object. User can access the location (array) using the pointer.
Using this makes our code efficient and smart to handle different sizes of input during the execution of code and allocate memory accordingly.

Code :

array_pointer = new int[total_user_entries];

array_pointer : Pointer to store the returned pointer to array.
new : Operator to allocate memory.
int : Data type
total_user_entries : Size of array of entered data

 

4. Store user data in the allocated space

Code :

for(loop_count = 0; loop_count < total_user_entries; loop_count++){

       
        *(array_pointer+loop_count) = temporary[loop_count];

    }

We use a ‘for()’ loop to access array items one by one.
temporary : In every iteration we store the user input from temporary variable to allocated space which is accessed using pointer – array_pointer.

*(array_pointer+loop_count) : pointer to access the current position of pointer to array.

(Note : loop_count value increases in every iteration and the respective consecutive memory locations are accessed. )

 

5. Print the array items

Code :

cout << "\n--Entered Items--";
for(loop_count = 0; loop_count < total_user_entries; loop_count++){

    cout << "\nItem " << loop_count+1 << ":  "<<    *(array_pointer+loop_count);

}

Step 4 uses pointer to access array locations to store values of items. Similarly, step 5 uses the same way to access the location of array. The main difference is that the integer pointer in this step is used to read and print the stored values in contrast to the purpose of step 4 of writing to that location.

Output :

--Entered Items--
Item 1: 23 
Item 2: 56

 

6. Deallocate Memory

Code :

delete []array_pointer;

Finally, we focus on freeing the memory in this step.
delete : delete operator is used to free up the space which was allocated to the array for storage.
[] : Square brackets specify that we want to free up space allocated for an array.
array_pointer : Starting location of the array for which memory is supposed to be freed.

( Note : This is probably the most important step in the procedure. The ‘delete’ operator ensures that the limited computer memory is efficiently used. The memory allocated to finished processes is freed and made available for new processes. )

 

Complete Code :

#include<iostream>

using namespace std;

int main()
{
    int *array_pointer;     //Pointer to integer array
    int total_user_entries = 0;     //integer to store total item entries
    int loop_count = 0;      //counter for loop
    int temporary[50];      //temporary storage variable
    int flag = 0;

    cout << "\nEnter item entries: \n(Enter -1 to terminate input)\n";

   while(flag == 0){

        cout << "\nEnter item " << loop_count+1 << ": ";
        cin >> temporary[loop_count];                                 
        if(temporary[loop_count] == -1)
            flag = 1;

        loop_count++;

    }

    total_user_entries = loop_count - 1;


    array_pointer = new int[total_user_entries];        


    for(loop_count = 0; loop_count < total_user_entries; loop_count++){

        *(array_pointer+loop_count) = temporary[loop_count];          

    }


    cout << "\n--Entered Items--";
    for(loop_count = 0; loop_count < total_user_entries; loop_count++){

        cout << "\nItem " << loop_count+1 << ":  "<< *(array_pointer+loop_count);     

    }
    cout<<"\n\n";

    delete []array_pointer;    

    return 0;
}

 

 

Output :

Enter item entries:
(Enter -1 to terminate input)

Enter item 1: 23

Enter item 2: 56

Enter item 3: -1

--Entered Items--
Item 1: 23
Item 2: 56

 

You may also learn:

Pointers and references in C++

Therefore, we have learned how to dynamically change size of arrays in C++.

One response to “How to change array size dynamically in C++”

  1. Sanmati Dugad says:

    It was quite helpful. Thank you Prajwal Khairnar.

Leave a Reply