我需要帮助来编写此代码:写名字时出现段错误。
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
字符分配内存,而是为one字符分配内存,并使用值50
对其进行初始化。您打算使用[50]
代替(50)
。
即使如此,您似乎仍以为listeEmployee
是一个数组,但是您尝试为多个元素输入时仅为数组中的第一个元素分配内存。对于每个数组元素的每个new
成员,您需要一次name
,例如在循环体内。
也不要对listeEmployee
使用指针。无论将数组传递给函数的位置,请使用std::vector
而不是原始数组,然后可以编写(需要#include<vector>
)
void saisie(std::vector<employee>& listeEmployee)
您将可以随时用listeEmployee
来获得listeEmployee.size()
的正确大小,而传递时不会出错。