Sign in to follow this  

Set c++ array length

This topic is 3413 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

This topic is 3413 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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