Sign in to follow this  
Yamulley

Set c++ array length

Recommended Posts

rip-off    10976
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 changes
void 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().

Share this post


Link to post
Share on other sites
ToohrVyk    1595
In C++, arrays are static. Their size is determined at compile time when they are defined, either explicitly or implicitely:
int array[10]; // size 10
int 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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this