这里的链表程序哪里不妥?为什么会有访问地址冲突的现象?

typedef struct No {
 string name;
 struct No* next;
}Node,  * pNode;

pNode list(void) {
 string val;
 pNode HEAD = (pNode)malloc(sizeof(Node));
 if (HEAD == nullptr) {
  cout << "分配内存失败!" << endl;
  exit(-1);
 }
 pNode end = HEAD;
 end->next = nullptr;
 int i;
 cout << "请输入人数" << endl;
 cin >> i;
 cout << "请输入姓名" << endl;
 for (int j = 0; j < i; j++) { 
  cin >> val;
  pNode p_end = (pNode)malloc(sizeof(Node));
  if (p_end == nullptr) {
   cout << "分配内存失败!" << endl;
   exit(-1);
  }
  p_end->name = val;
  end->next = p_end;     //出错点:访问地址冲突
  p_end->next = nullptr;
  end = p_end;
 }
 return HEAD;
}


我是北方栖姬
浏览 945回答 1
1回答

AAnonymous

个人觉得问题在于,不应当使用C风格的struct。既然C++中struct是一个类,你就应当写成C++的类。使用new去创建对象。malloc不会调用构造函数,只是分配那么大一块内存,而且C++里,string也是一个类,这样可能导致某些地方内存访问出问题。
打开App,查看更多内容
随时随地看视频慕课网APP