Set c++ array length

Started by
1 comment, last by ToohrVyk 15 years, 8 months ago
how can i set c++ array length? int *Array; void something() { //here i need set length //set array length to 20 }
Advertisement
By using a dynamic list data structure, such as std::vector<>:
#include <vector>std::vector<int> Array;void something(){     Array.resize(20);     // ...}


To avoid globals:
#include <vector>// Pass by reference: caller sees changesvoid something(std::vector<int> &Array){     Array.resize(20);    // ...}


Vectors can be used like arrays, with some handy additional functionality. You can reference elements using [] notation, or with iterators. You can query the size of the array by using its size() member function. You can add elements by using push_back().
In C++, arrays are static. Their size is determined at compile time when they are defined, either explicitly or implicitely:
int array[10]; // size 10int array[] = { 1, 2, 3 }; // size 3


If you wish to use an array-like structure that can change dimensions at runtime, you can use std::vector which, in your example, would behave as:
std::vector<int> array;void something(){  array.resize(20);}


You then have the raw solution consisting of using the operators new[] and delete[], as such:
int *Array;void something(){  int *temp = new int[20];  std::swap(temp, Array);  delete [] temp;}


However, this method has the problem that it does not store size information, and thus cannot copy the contents from the previous array to the new one. It can also cause performance problems due to overuse of memory allocation. Last but not least, it is not exception-safe and should not be used like shown above with local or class variables unless you can provide acceptable RAII memory ownership policies.

This topic is closed to new replies.

Advertisement