How come my arrary won't take a user entered size?Code:void main()
{
const int size;
cout << "Please enter a amount of lights" << endl;
cin >> size;
int lights[size];
for (int i = 0; i < n; i++)
{
lights[i] = 1;
}
}
Printable View
How come my arrary won't take a user entered size?Code:void main()
{
const int size;
cout << "Please enter a amount of lights" << endl;
cin >> size;
int lights[size];
for (int i = 0; i < n; i++)
{
lights[i] = 1;
}
}
Firstly, size is const. More importantly, standard C++ does not provide for variable length arrays. Use a std::vector instead, e.g.,
Code:#include <iostream>
#include <vector>
int main()
{
std::vector<int>::size_type size;
std::cout << "Please enter a amount of lights" << std::endl;
std::cin >> size;
std::vector<int> lights(size, 1);
// No need for the init loop any more.
// ... do other stuff ...
}
We have not got to vectors in class. I don't know if I can use that I will play with it anyway thanks.
If you cannot use the standard containers, then it implies that you should use new[] and delete[]. If you cannot use that either, then you should create a large enough array, and only use the first size elements of that array.
Alright I'll see what I can do I'm trying to make a program using recursion to set all of the lights to off (0) when they are initially set to on (1).
Write a function to print the integers from 0 to size-1, having only the current number and the size as the parameters. Then add a parameter for the array of lights and start setting the lights to off instead of printing integers.Quote:
Alright I'll see what I can do I'm trying to make a program using recursion to set all of the lights to off (0) when they are initially set to on (1).
Alternatively, write a function to print the integers from size-1 to 0, having only the current number as the parameter. Then add a parameter for the array of lights and start setting the lights to off instead of printing integers.
try like so???
in your lights .cpp
Code:
void lights::makeArray(){
int size;
cout << "Please enter a amount of lights" << endl;
cin >> size;
int lights[size];
for (int i = 0; i < size-1; i++)
{
lights[i] = 1;
}
}
Nope. That gets the value into size perfectly well, but it declares a variable-length array, which is apparently not standard C++.
(BTW, the for loop should likely have this condition: "i < size".)
laserlight has already supplied a vector example. Here's a dynamic memory allocating one.
The delete statement frees the memory allocated by new, and should be called after you are done using the array. Otherwise you have a memory leak.Code:// after reading int size from the user:
int *lights = new int[size];
// ... use the array lights ...
delete [] lights;
Also,
http://cpwiki.sf.net/Void_main
Get rid of the void main and use int main.