声明了一个结构变量,它是另一个结构的动态数组。为什么下面的 C++ 程序会崩溃?
Declared a structure variable which is a dynamic array of another structure. Why is the following C++ program being crashed?
我已经声明了一个结构变量,它是另一个结构的动态数组,但程序每次都崩溃。我哪里做错了?需要采取哪些必要步骤?我正在使用 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++ 中使用。您应该改用 new
或 new[]
。
e.project_list = new Project[2];
结构 Project
使用类型 std::string
的 object
struct Project{
int pid;
string name;
};
所以首先你需要包括 header <string>
#include <string>
要创建(和销毁)此类型的 object,应调用其构造函数(和析构函数)。但是 C 函数 malloc 对构造函数一无所知。而且它甚至不初始化分配的内存。
所以在这些陈述中
e.project_list[0].pid = 100;
e.project_list[0].name = "游戏";
可以访问未创建的 std::string
类型的 object。他们的构造函数没有被调用。
使用 operator new 代替 malloc
e.project_list = new Project[2];
我已经声明了一个结构变量,它是另一个结构的动态数组,但程序每次都崩溃。我哪里做错了?需要采取哪些必要步骤?我正在使用 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++ 中使用。您应该改用 new
或 new[]
。
e.project_list = new Project[2];
结构 Project
使用类型 std::string
struct Project{
int pid;
string name;
};
所以首先你需要包括 header <string>
#include <string>
要创建(和销毁)此类型的 object,应调用其构造函数(和析构函数)。但是 C 函数 malloc 对构造函数一无所知。而且它甚至不初始化分配的内存。
所以在这些陈述中
e.project_list[0].pid = 100; e.project_list[0].name = "游戏";
可以访问未创建的 std::string
类型的 object。他们的构造函数没有被调用。
使用 operator new 代替 malloc
e.project_list = new Project[2];