【问题标题】:how to dynamically allocate character space to a structure field如何为结构字段动态分配字符空间
【发布时间】:2019-12-22 14:35:21
【问题描述】:

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

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

【问题讨论】:

  • 您是否尝试过使用std::string
  • 当然我已经包含了string的包!
  • 如果你被允许使用std::string,那么永远不要使用new char(50);char *name;,而是使用std::string name;,这样代码会更简单,更不容易出错。
  • listeEmployee-&gt;name=new char(50); 是你的错误。
  • 不要在 C++ 中使用typedef struct employee {...} employee;。这在 C 中是必需的,但在 C++ 中是完全多余的。只需改用struct employee { ... };

标签: c++ function char structure allocation


【解决方案1】:

只是不要使用char* 来保存字符串。请改用std::string(需要#include&lt;string&gt;):

struct employee{
    std::string name;
    float salary;
    int stage;
};

现在您不必动态分配任何东西。可以直接用cin &gt;&gt;输入name


您原来的new 没有为50 字符分配内存,它为一个 字符分配内存并使用值50 对其进行初始化。你的意思是使用[50] 而不是(50)

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


也不要为listeEmployee 使用指针。无论您将数组传递给函数的何处,请使用std::vector 而不是原始数组,然后您可以编写(需要#include&lt;vector&gt;

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

您将能够随时通过listeEmployee.size() 获得正确大小的listeEmployee,而不会出错。

【讨论】:

  • @kouzin 纯粹为了感谢别人的评论在这里不太受欢迎。如果有人回答了您的问题,请参阅 here 了解您可以(但不必)做的事情。
猜你喜欢
  • 2018-04-07
  • 1970-01-01
  • 2021-08-11
  • 2017-02-15
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多