开发者

Where is the access violation is my code?

I'm getting an Access Violation whe开发者_如何学运维n attempting to run this code which finds prime numbers in a bound.

int main () {
    cout << "Program initialized successfully. Please wait for the next message to appear." << endl << endl ;

    int Primes[51] ;
    int runner = 0 ;
    int chaser = 0 ;
    int bound = 0 ;
    int count = 0 ;

    cout << "Please enter the maximum boundary of the calculation : " ;

    cin >> bound ;

    cout << endl << "The number you've entered, " << bound << ", has been accepted. Please wait for the calculations." << endl ;

    if (runner <= bound ) {
        Primes[0] = 2;
        Primes[1] = 3;
        Primes[2] = 5;
        Primes[3] = 7;
        Primes[4] = 11;
        count = 4;

        for ( runner = 11 ; runner <= bound ; runner ++ ) {
            while ( runner % Primes[chaser] != 0 ) {
                for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) {
                    if ( runner % Primes[chaser] == 0 ) {
                        count ++ ;
                        Primes[count] = runner;
                    }
                }
            }
        }

        int chaser_count;
        cout << "Here's the primes computer discovered : " << endl ;
        for ( chaser_count = 0 ; chaser_count <= count ; chaser_count ++ ) {
            cout << Primes[chaser_count] << endl ;
        }
        cout << "There is " << count << " primes discovered." << endl ;
    }
    return 0;
}

The program runs fine until to the line of calculation : if(runner <= bound)

I got a Access Violation.

I Kind of know what an Access Violation is, but I don't know what raised it.

edit:

I got 2 answers now stating that I may have something like Primes[50] going on, but I seriously doubt so, because I get the error immediately after I specify the bound, 12.

Thanks for the guy who de-comment this.

I'm using Dev-C++.

I found the place where the error was raised. Thanks for anyone who commented and answered for me. It is an logical error that I didn't found that leads to a Prime[51].

Thank you all for helping me.


Here :

for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) {

you didn't initialize you Primes array with 0, so the loop can loop over and over and chaser can be bigger than 51 (the size of you Primes array) and then Primes[something_bigger_than_50] will raise an access violation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜