c++ - Array Related Error - Invalid Types..? -
i making simple program related arrays. code:
#include <iostream> #include <cmath> using namespace std; int main() { int a; cout << "please enter length of array: " << endl; cin >> a; bool array[a]; (int n = 0; n < a; n++) { array[n] = true; } array[0] = false; array[1] = false; (int k = 2; k < a; k++) { if (array[k] == true){ (int = 0; pow(k,2)+ i*k < a; i++) { array[ pow(k,2) + * k] = false; } } } (int j = 0 ; j < ; j++){ if (array[j] == true){ cout << j <<endl; } }
}
i error in line
array[ pow(k,2) + * k] = false;
it says
"invalid types" ||=== build: debug in test (compiler: gnu gcc compiler) ===| c:\users\momo\documents\codeblocks projects\test\main.cpp||in function 'int main()':| c:\users\momo\documents\codeblocks projects\test\main.cpp|21|error: invalid types 'bool [(((sizetype)(((ssizetype)a) + -1)) + 1)][__gnu_cxx::__promote_2<int, int, double, double>::__type {aka double}]' array subscript| ||=== build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
that error. trying switch java c++. such kind of error new me never encountered such error in java. can guys , girls me understand means? , can resolve it? thanks.
welcome! have entered whole new world programming in c++. let me introduce c++ standard library (often called stl) (http://www.cplusplus.com reference). containers want use in everyday life want consider 1 standard library.
in particular instance, cannot instantiate array @ runtime have done above. cannot instantiate array on stack size determined @ runtime. need dynamically allocate memory on heap or use stl container (std::vector<>
advised). how have written code
#include <iostream> #include <cmath> #include <vector> using namespace std; int main() { int a; cout << "please enter length of array: " << endl; cin >> a; vector<bool> array(a); (int n = 0; n < a; n++) { array[n] = true; } array[0] = false; array[1] = false; (int k = 2; k < a; k++) { if (array[k] == true){ (int = 0; pow(k,2)+ i*k < a; i++) { array[ static_cast<size_t>(pow(k,2) + * k) ] = false; } } } (int j = 0 ; j < ; j++){ if (array[j] == true){ cout << j <<endl; } } return 0; }
to explain more here. following line
std::vector<bool> array(n)
initializes vector (for sake of simplicity) n
elements.
more information vector class can found here (http://www.cplusplus.com/reference/vector/vector/?kw=vector)
Comments
Post a Comment