简体   繁体   中英

very strange C++ error

I have encountered a very strange problem when I am writing code, Here is my C++ code:

#include <iostream>
using namespace std;

int main()
{
    int qnum;
    cin >> qnum;
    int series[3];
    cin >> series[3];
    cout << qnum;
}

For example, If I input 2 for qnum and 5 for series[3], The value of qnum will be overridden in the last line of code.This problem will only occurs when the input for series is 3. The only solution for new is add "static" attribute to qnum, Like this:

#include <iostream>
using namespace std;

int main()
{
    static int qnum;
    cin >> qnum;
    int series[3];
    cin >> series[3];
    cout << qnum;
}

Any ideas?

There is no series[3] . There are only series[0] , series[1] and series[2] (arrays go from 0 to N-1).

You are writing off the end of your array, which causes undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM