大家好,我需要帮助来编写这段代码:我在写名称时遇到了段错误。
typedef struct employee{
char *name;
float salary;
int stage;
}
employee;
void saisie(employee* listeEmployee,int nb_employee){
listeEmployee->name=new char(50);
for(int i=0;i<nb_employee;i++){
cout<<"Enter the name of employee, his salary and the stage" <<i<<endl;
cin>>listeEmployee[i].name;
cin>>listeEmployee[i].salary;
cin>>listeEmployee[i].stage;
}
}
最佳答案
只是不要使用 char*
保存字符串。使用 std::string
相反(需要 #include<string>
):
struct employee{
std::string name;
float salary;
int stage;
};
现在您不必动态分配任何东西。您可以输入name
与 cin >>
直接。
你原来的new
不为 50
分配内存字符,它为 一个 字符分配内存并用值 50
初始化它.你打算使用 [50]
而不是 (50)
.
即便如此,您似乎还是假设 listeEmployee
是一个数组,但您只为数组中的第一个元素分配内存,而您尝试输入多个元素。你需要 new
每个name
一次每个数组元素的成员,例如在循环体内。
不要对 listeEmployee
使用指针任何一个。无论你在哪里将数组传递给函数,使用 std::vector
而不是原始数组,然后您可以编写(需要 #include<vector>
)
void saisie(std::vector<employee>& listeEmployee)
你将能够得到正确大小的listeEmployee
与 listeEmployee.size()
任何时候都可以毫无错误地传递它。
关于c++ - 如何将字符空间动态分配给结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59445142/