Possible Duplicate:
Can you resize a C++ array after initialization?
I need to do the equivalent of the following C# code in C++
Array.Resize(ref A, A.Length - 1);
How to achieve this in C++?
Possible Duplicate:
Can you resize a C++ array after initialization?
I need to do the equivalent of the following C# code in C++
Array.Resize(ref A, A.Length - 1);
How to achieve this in C++?
Raw arrays aren't resizable in C++.
You should be using something like a Vector class which does allow resizing..
std::vector
allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).
The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector
is for:
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.resize(v.size()-1);
You cannot do that, see this question's answers. You may use std:vector instead.
You cannot resize array, you can only allocate new one (with a bigger size) and copy old array's contents.
If you don't want to use std::vector
(for some reason) here is the code to it:
int size = 10;
int* arr = new int[size];
void resize() {
size_t newSize = size * 2;
int* newArr = new int[newSize];
memcpy( newArr, arr, size * sizeof(int) );
size = newSize;
delete [] arr;
arr = newArr;
}
code is from here http://www.cplusplus.com/forum/general/11111/.
std::vector
orTry realloc()
int size,*a;
a = 0;
size = 3;
a = (int*) realloc(a,size*sizeof(int));
a[0] = 16;
a[1] = 24;
a[2] = -5;
size ++;
a = (int*) realloc(a,size*sizeof(int)); //Reallocates more memory to the 'array'
a[3] = 44;
free(a); //Free the memory you allocated once you are done using it.
To call realloc()
remember to #include <cstdlib>