Constant Expression error and some other errors

I received some errors. I can't seem to find the solution.

1
2
3
4
5
6
7
8
9
10
11
12
1
1>  prime.cpp
prime.cpp(13): error C2057: expected constant expression
prime.cpp(13): error C2466: cannot allocate an array of constant size 0prime.cpp(13): error C2133: 'array' : unknown size
prime.cpp(14): error C2057: expected constant expression
prime.cpp(14): error C2466: cannot allocate an array of constant size 0
prime.cpp(14): error C2133: 'brray' : unknown size
prime.cpp(21): error C2668: 'sqrt' : ambiguous call to overloaded function
math.h(589): could be 'long double sqrt(long double)'
math.h(541): or       'float sqrt(float)'
ath.h(127): or       'double sqrt(double)'
1>          while trying to match the argument list '(int)'prime.cpp(44): warning C4018: '<' : signed/unsigned mismatch
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void findPrimes(vector<int>& primes, int n) {     
	
	int array[n-1];
	bool brray[n];
	for (int i=2; i < n; i++){
		brray[i] = true;
	} //Make all index true to indicate primeness

	int p;

	for (p = 2; p < sqrt(n); p++){
		for(int q=p; q < n; q+=p){ 
			if(q==p)
				continue;
			else
				brray[q]=false;
		}
	}

	for (int i=2; i < n; i++){
		if(brray[i] == true)
			primes.push_back(1);
		else
			primes.push_back(0);
	}
    
}    

int main(){
    vector<int> primes;
         
    findPrimes(primes, 10000);
        
    for(int i = 0; i < primes.size(); i++)
            cout<< primes[i] << std::endl;      

    
    return 0;
}
The compiler needs to know (at compile time) which will be the size of your array.
so int array[n]; is illegal
Why don't you use vectors instead?

sqrt( n ); n is an integer, and it does not exist a sqrt that takes an integer as argument. Cast it.
First 5 errors happen because you can only declare static arrays of constant size ( int arr[5]; is fine, but int n = 5; int arr[n]; is not. Either dynamically allocate the memory yourself (int* arr = new int[n];) or use a vector.
The last error is because there are several overloads of sqrt, but none of them take an integer argument, so the compiler doesn't know which to use. You could use sqrt( float(n) ) or sqrtf(n) but the best solution would be p*p<=n as sqrt is much slower than multiplication. Also note the <=. Otherwise you'll get 4 as a prime.
Topic archived. No new replies allowed.