I was making a simple program related to arrays. My Code:
#include <iostream> #include <cmath> using namespace std; int main() { int a; cout << "Please enter the length of the array: " << endl; cin >> a; bool array[a]; for (int n = 0; n < a; n++) { array[n] = true; } array[0] = false; array[1] = false; for (int k = 2; k < a; k++) { if (array[k] == true){ for (int i = 0; pow(k,2)+ i*k < a; i++) { array[ pow(k,2) + i * k] = false; } } } for (int j = 0 ; j < a ; j++){ if (array[j] == true){ cout << j <<endl; } } }
I get an error in the line
array[ pow(k,2) + i * 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}]' for array subscript| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===| That is the error. I am trying to switch from Java to C++. However such kind of error is new to me as I never encountered such error in Java. Can you guys and girls help me understand what this means? And what can I do to resolve it? Thanks.
bool array[a];This is not legal ANSI C++. Array sizes in C++ must be declared using a compile-time expression, not at runtime. You're using a compiler extension.Math.powas an array index.