Can't u use an array?
#include <iostream>
using namespace std;
main()
{
short variable_number;
cin >> variable_number;
int *my_var = new int[variable_number];
for(int i = 0; i< variable_number; i++)
{
my_var[i] = 1;
}
return 0;
}
To be a little pedantic, that code has the potential to leak memory, so you should be careful. Every new should have a delete to go with it, so the snippet should be:
#include <iostream>
int main()
{
short variable_number;
std::cin >> variable_number;
int *my_var = new int[variable_number];
for(int i = 0; i< variable_number; i++)
my_var[i] = 1;
// Do things with the array
delete[] my_var; // Free the memory that we used for the array when it's no longer needed
return 0;
}
Even better, use std::vector instead:
#include <iostream>
#include <vector>
int main()
{
short variable_number;
std::cin >> variable_number;
std::vector< int > my_var(variable_number);
for(int i = 0; i< variable_number; i++)
my_var[i] = 1;
return 0;
}
This way, the memory management is taken care of for you.
There are people who say that you should learn to use arrays properly before you start with std::vector , and they've probably got a point, but at the end of the day the slight overhead is better than a bunch of memory leaks :o)
ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9