devxlogo

Resizing Dynamic Array

Resizing Dynamic Array

Question:

int num = 50;int **stuff;stuff = new int* [num];for (int i = 0 ; i < num ; ++i)      stuff[i] = new int [num];

The code above is copied from another question. Say the above array is a matrix where each row has a number of columns, how do you increase the size of the array to add another row?

Answer:
While many people like to use new and delete to manage memory, they don't give you much control. The old C favorites, malloc(), free(), and friends, are still helpful in C++.

Memory allocated with malloc() can be resized using realloc(). The only disadvantage is that, if you have an array of class objects, the constructors are not automatically called for each object in the array. Similarly, the destructors are not automatically called on objects when you call free(). However, in cases such as yours where the array is simply of integers, this is not an issue.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist