声明一个结构变量,它是另一个结构的动态数组。为什么下面的C++程序会崩溃?

我已经声明了一个结构变量,它是另一个结构的动态数组,但程序每次都崩溃。我哪里做错了?需要采取哪些必要步骤?我正在使用 DEVC++。

#include<iostream>
#include<cstdlib>

using namespace std;

struct Project{
    int pid;
    string name;
};

struct employee{
    int eid;
    string name;
    Project *project_list;
};

int main(){
   struct employee e;
   e.eid = 123;
   e.name = "789";
   e.project_list = (Project *)malloc(2 * sizeof(Project));

   e.project_list[0].pid = 100;
   e.project_list[0].name = "Game";
}

回答

malloc()不会正确初始化编译类,不应在 C++ 中使用。您应该使用newnew[]代替。

e.project_list = new Project[2];

  • @SaubhikPaladhi: If this was C code, you wouldn't be using a `string` class that is assumed to already be initialized. Your bug occurred because you're mixing C constructs and C++ constructs together.

以上是声明一个结构变量,它是另一个结构的动态数组。为什么下面的C++程序会崩溃?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>