简体   繁体   English

非常奇怪的C ++错误

[英]very strange C++ error

I have encountered a very strange problem when I am writing code, Here is my C++ code: 我在编写代码时遇到了一个非常奇怪的问题,这是我的C ++代码:

#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: 例如,如果我为qnum输入2,为series [3]输入5,则qnum的值将在代码的最后一行中被覆盖。仅当series输入为3时,才会出现此问题。new的唯一解决方案是向qnum添加“ static”属性,如下所示:

#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] . 没有series[3] There are only series[0] , series[1] and series[2] (arrays go from 0 to N-1). 只有series[0]series[1]series[2] (数组从0到N-1)。

You are writing off the end of your array, which causes undefined behaviour. 您正在注销数组的末尾,这将导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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