Table of variable size
May 10, 2014 at 4:44pm UTC
Hello,
I would like to create a table but I dont know how big. Thats why I want to use variable to describe its size. Something like that:
1 2
int x = 5; //I will use a function to set x
int Table[x];
What should I do to make it work?
May 10, 2014 at 5:06pm UTC
Use vector:
1 2
int x = 5;
std::vector<int > table(x);
Or use dynamic memory allocation:
1 2 3 4 5
int x = 5;
int * table = new int [x];
//Do not forget to delete array whn you are done!
//Or face memory leak
delete [] table;
May 10, 2014 at 5:11pm UTC
and if I decide to use dynamic memory allocation can I do things like that:
1 2 3 4
for (int y = 0; y < x; y++)
{
Table[y] = SomeFunction();
}
or it works in some other way?
May 10, 2014 at 5:13pm UTC
You can do this with both vector and dynamic allocation. The both works the same way. But vector handles memory automaticly and have many useful member functions.
May 10, 2014 at 5:27pm UTC
Thanks for you help ;)
Topic archived. No new replies allowed.