C++ g+的分段错误+;在Linux Ubuntu中,但不使用g++/在Windows中,在C+;中打印字符字符串时+;

C++ g+的分段错误+;在Linux Ubuntu中,但不使用g++/在Windows中,在C+;中打印字符字符串时+;,c++,linux,segmentation-fault,g++,mingw,C++,Linux,Segmentation Fault,G++,Mingw,我有一个计划,它: 创建一个包含3个char指针的数组,char*z_str[3] 分配类型为char的动态内存对象,并将返回的指针分配给这些char指针 提示用户提供输入字符串 打印提供的字符串 源代码: #include <iostream> using namespace std; int main() { char *z_str[3]; int i; for(i = 0; i < 2; i++) { z_str[i]

我有一个计划,它:

  • 创建一个包含3个
    char
    指针的数组,
    char*z_str[3]
  • 分配类型为
    char
    的动态内存对象,并将返回的指针分配给这些
    char
    指针
  • 提示用户提供输入字符串
  • 打印提供的字符串

  • 源代码:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        char *z_str[3];
        int i;
    
        for(i = 0; i < 2; i++)
        {
            z_str[i] = new char [30];
            if(z_str[i] == NULL)
            {
                cout << "Memory for String " << i+1 << " could not be allocated!" << endl;
                cout << "Program terminates.";
                return 1;
            }
        }
    
        cout << endl << endl;
    
        cout << "Please input the first string [max.29 characters]:" << endl;
        cin >> z_str[0]; 
        cout << endl;
    
        cout << "Please input the second string [max.29 characters]:" << endl;
        cin >> z_str[1]; 
        cout << endl;
    
        cout << "Please input the third string [max.29 characters]:" << endl;
        cin >> z_str[2]; 
        cout << endl << endl;
    
    
        cout << "First string is:" << endl;
        cout << z_str[0] << endl << endl;
    
        cout << "Second string is" << endl;
        cout << z_str[1] << endl << endl;
    
        cout << "Third string is:" << endl;
        cout << z_str[2] << endl << endl;
    
        return 0;
    }
    

    现在,如果我在Windows 10中使用g++/MingW编译相同的代码,那么在PowerShell中一切都会正常工作:

    
    Please input the first string:
    string1
    
    Please input the second string:
    string2
    
    Please input the third string:
    string3
    
    
    First string is:
    string1
    
    Second string is
    string2
    
    Third string is:
    string3
    

      为什么我在Linux Ubuntu中会遇到G+ +的分割错误,而在Windows中,当在C++中打印字符字符串时,不是用G++/MIW来分割错误?
    循环

    for(i = 0; i < 2; i++)
    

    所有这些都有更好的解决方案,我建议使用一组对象:


    上面的循环保证在数组的所有元素上迭代。

    投票以键入结束。你犯了一个错误。for循环是for(i=0;i<2;i++)
    ,但它应该是for(i=0;i<3;i++)
    ,因为数组有3个元素。按照现在的情况,z_str[2]尚未初始化。在21世纪,我们将使用
    std::array
    。它很容易防止这个问题。是的。自2011年以来,未经处理的数组或
    新建的
    。@RobertSsupportsMonicaCellio:我明白了,这就是为什么我写了一条评论而不是答案。但我认为告诉你你正在向落后几十年的人学习是很有用的。请注意,
    new
    如果失败不会返回NULL,它会抛出一个异常。为了避免将来出现这种情况,你可以对原始数组使用
    sizeof
    ,或者
    std::array
    @Someprogrammerdude初学者的错误。我很生气我没有抓住它。谢谢你提供的有用提示。
    for(i = 0; i < 2; i++)
    
    for(i = 0; i < 3; i++)
    
    std::array<std::string, 3> z_str;
    
    for (auto& str_ptr : z_str)
        str_ptr = new char[30];