Jump to content
  • Advertisement
Sign in to follow this  
Yamulley

Set c++ array length

This topic is 3629 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

how can i set c++ array length? int *Array; void something() { //here i need set length //set array length to 20 }

Share this post


Link to post
Share on other sites
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 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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!