Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
May 23, 1999

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.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date