为什么下面的C ++代码为此特定输入给出分段错误?

时间:2018-12-14 12:31:35

标签: c++ segmentation-fault

int main(){
    int n;
    cin>>n
    cin.ignore(32767,'\n');
    string arr[n],temp;
    for(int i=0;i<n;i++){
        getline(cin,temp);
        arr[i]=temp;
    }
}

输入
10
游客
彼得
wjmzbmr
yeputons
vepifanov
斯科特乌
oooooooooooooooo
订阅者
rowdark
tankengineer

我的代码对于所有其他输入(即使当n = 10时)也运行良好,但是对于此特定输入(如上所述),它给出了分段错误。

1 个答案:

答案 0 :(得分:1)

您的代码可能无法原样编译,并且您正在使用C ++不支持的VLA:s,因此很难重现您的问题。请尝试使用C ++容器(例如std::vector)来避免这种情况。示例:

#include <iostream>
#include <vector>

int main() {
    int n;
    std::cin >> n;
    std::cin.ignore(); // discard the '\n' still in the buffer

    // declare a standard C++ container, like a vector of strings
    std::vector<std::string> arr(n);

    for(int i=0; i<n; ++i) {
        std::getline(std::cin, arr[i]);
    }

    std::cout << "VALUES:\n";
    for(auto& s : arr) {
        std::cout << s << "\n";
    }
}