Changing the size of arrays at runtime in C++ is demanding. In this simple code, we will learn how to change the size of an array of data at runtime. In this order, a structure of data is designed and a pointer is used to point to the allocated part of memory to store the data in the form of a stack, and the size of the allocated memory is changed while we push and pop data into the stack.
I have assumed that you know what a stack is and how it works.
Using the code
First of all, a structure of data is designed as follows:
This is just a simple structure. You can change it to whatever you are interested in.
Then, a pointer with the structure data type is defined.
dataStruct * objStruct;
It is crucial to set the pointer to
NULL at the beginning. It is done in my code in the class constructor.
objStruct = NULL;
Next, you can change the size of the allocated memory of your pointer at any time you need.
objStruct = (dataStruct*) realloc (objStruct,
iStackCounter * sizeof(dataStruct));
In the line above,
iStackCounter stores the number of stored items in the stack. Therefore, the allocated size for the memory should be a multiplication of the number of items and the size of the structure. You can call this line any time you need.
The rest of the code is the basic storing of data in a stack, and finally in the main function, by calling
pop functions, you can put and fetch data from your stack. While you put a new item into the stack, the size of memory is changed automatically and you do not need to worry about the size of your stack. The allocated size is decreased when you pop data from the stack until the stack becomes empty.
You might see compiler error(s) when you want to run the attached code. First, check the header files. I have used GCC compiler in UBUNTU and the header names might be different than yours.
Hope you find this useful.