Dynamic Memory Allocation — Part1

ANSIF
1 min readApr 29, 2024

--

#include<iostream>

int main()
{
int *vector = nullptr;

int size = 0;
for(int i=0;i<10;i++)
{
int *temp = new int[size+1];

for(int j=0;j<size;j++)
{
temp[j] = vector[j];
}
delete[] vector;
vector = temp;

vector[size] = i+1;
size++;
}

for(int i=0;i<10;i++)
{
std::cout<<vector[i]<<" ";
}

return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10

In this code:

  • We start with a nullptr pointer.
  • We dynamically allocate memory for one element at a time and resize the array as needed.
  • We copy the existing elements to the new array and add the new element.
  • We print the elements of the array.
  • Also temp is a local variable, and its memory is automatically released when it goes out of scope exiting the loop
  • Finally, we deallocate the memory to avoid memory leaks.

This will also output: 1 2 3 4 5 6 7 8 9 10.

This approach allows the array to dynamically resize itself as elements are added, without requiring a fixed initial size.

--

--

ANSIF
ANSIF

No responses yet