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

标签 c++ function char structure allocation

大家好,我需要帮助来编写这段代码:我在写名称时遇到了段错误。

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;
};

现在您不必动态分配任何东西。您可以输入namecin >>直接。


你原来的new不为 50 分配内存字符,它为 一个 字符分配内存并用值 50 初始化它.你打算使用 [50]而不是 (50) .

即便如此,您似乎还是假设 listeEmployee是一个数组,但您只为数组中的第一个元素分配内存,而您尝试输入多个元素。你需要 new每个name一次每个数组元素的成员,例如在循环体内。


不要对 listeEmployee 使用指针任何一个。无论你在哪里将数组传递给函数,使用 std::vector而不是原始数组,然后您可以编写(需要 #include<vector> )

void saisie(std::vector<employee>& listeEmployee)

你将能够得到正确大小的listeEmployeelisteEmployee.size()任何时候都可以毫无错误地传递它。

关于c++ - 如何将字符空间动态分配给结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59445142/

相关文章:

c++ - C++ 中 std::fstream::X 和 std::ios::X 的区别

特定时间段后的 C++ 调用函数 - 无提升

c - 将双指针传递给函数以获取链表的起始地址(C)

java - Java 中的字符数组迭代 - 改进算法

c++ - 将文本文件读入 char 数组。 C++ ifstream

c++ - 通过 LAN : characters or ints? 向嵌入式设备发送自定义命令

c++ - 查找模板相等运算符

swift - 函数调用明确还是 Xcode 8 错误?

mysql - mysql查询where条件比较char字段与int 0的一些现象

c++ - 动态加载是否与 C++ 标准严格兼容?