如何将字符空间动态分配给结构字段

问题描述 投票:0回答:1

我需要帮助来编写此代码:写名字时出现段错误。

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;
    }
}
c++ function char structure allocation
1个回答
2
投票

仅不要使用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()的正确大小,而传递时不会出错。

© www.soinside.com 2019 - 2024. All rights reserved.