首页 > 解决方案 > 为什么以下 C++ 代码会为此特定输入提供分段错误?

问题描述

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 个
旅游
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
订户
rowdark
tankengineer

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

标签: c++segmentation-fault

解决方案


您的代码可能无法按原样编译,并且您使用的是 C++ 不支持的VLA:s,因此很难重现您的问题。尝试通过使用 C++ 容器(如 a 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";
    }
}

推荐阅读