Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize array in C++?

Tags:

c++

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++?

like image 918
softwarematter Avatar asked Sep 20 '10 08:09

softwarematter


People also ask

Can I resize an array in C?

There is no way to resize an array. You can simply create a new array of size 2, then copy all the data from the previous one to the new one. realloc does it for you with dynamic memory.

Can we resize arrays?

You cannot resize an array in C#, but using Array. Resize you can replace the array with a new array of different size.

Which method is used to resize an array?

Resize<T>(T[], Int32) Method.


1 Answers

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/.

like image 88
Insomniac Avatar answered Sep 24 '22 17:09

Insomniac