How to resize an array?

Pages: 12
Is the religious war finally over?

I'm sorry JoshuaCrotts, you had bad luck but here is a summary:
a) If you need an array for studying you may work with raw pointers but you have to be carefull because you could have some memory leaks.
They won't last any longer than your program runs but if it runs for to long then the program might crash or it might just use a huge amount of RAM.
1
2
3
4
5
6
7
8
int size;
std::cin >> size;
int* array = new int[size];

// do something

// this is important with raw pointers.
delete[] array; // delete array 

b) If you need an array to just be resizeable you should consider std::vector.
You don't need to delete the memory yourself so no memory leaks occur:
1
2
3
4
5
int size;
std::cin >> size;
std::vector<int> array(size); // create array with size elements

// do something, it will be deleted automatically 

Any STL-container, a deque, a vector or a list will all do what you want and if you just want the job done you should have a default container whenever you need one, vector is mine.
The difference between them is their implementation so you get some advantages here and some disadvantages there.
If you just want your task done choose any of them.
If you want to be serious about C++ and performance is important to you you should take a closer look on the advantages and disadvantages of those containers.
Last edited on
closed account (48T7M4Gy)
The new - delete combination is quite adequate and it can be easily extended by adding copy functionality to enable extending the resizing as many times as required.
Last edited on
When multiple people who have been around these forums for years learning and teaching C++ all tell you the same thing, I think that's a hint to buy a more up-to-date book on C++.
http://stackoverflow.com/a/388282/1959975

By the way, I'm not sure who reported your post or why.
By the way, I'm not sure who reported your post or why.

My guess would be that "Nazi" is a pretty offensive thing to call someone.
Topic archived. No new replies allowed.
Pages: 12