Sau*_*dhi -1 c++ struct dynamic-memory-allocation
我已经声明了一个结构变量,它是另一个结构的动态数组,但程序每次都崩溃。我哪里做错了?需要采取哪些必要步骤?我正在使用 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";
}
Run Code Online (Sandbox Code Playgroud)
malloc()不会正确初始化编译类,不应在 C++ 中使用。您应该使用new或new[]代替。
e.project_list = new Project[2];
Run Code Online (Sandbox Code Playgroud)