【问题标题】:C++ linked list not displaying String type variablesC++ 链表不显示字符串类型变量
【发布时间】:2026-01-26 13:55:02
【问题描述】:

我的struct Node 下有一个名为flavour 的字符串变量,每次我输入风味变量的字符串时,程序都会停止工作并最终什么也不打印。我已经通过使用不同的变量类型(例如整数和字符)对其进行了测试,这两种变量类型都可以正常工作,并且会打印出变量中的任何内容。

这是我的代码:

#include <iostream>
using namespace std;
struct Node { 
   string flavor;
   struct Node *next; 
}; 
struct Node* head = NULL;   
void insert(string data) { 
   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 
   new_node->flavor = data; 
   new_node->next = head; 
   head = new_node; 
} 
void display() { 
   struct Node* ptr;
   ptr = head;
   while (ptr != NULL) { 
      cout<<"First data is "<< ptr->flavor; 
      ptr = ptr->next; 
   } 
} 
int main() { 

    string input;
    cout<<"Enter a flavor!"<<endl;
    cin>>input;
    insert(input);

   cout<<"The linked list is: ";
   display(); 

   return 0; 
} 

这是结果,您可以看到cin&gt;&gt;input;insert(input) 之后的所有内容似乎都不起作用。我错过了什么吗?

【问题讨论】:

  • struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 啊!我的眼睛!

标签: c++ string list oop linked-list


【解决方案1】:

使用 new 而不是 malloc 进行分配。当前,您的代码使字符串 Node::flavour 处于未初始化状态,因此当您尝试为其分配值时,它正在尝试释放或访问无效的内存位置。

Node* new_node = new Node;

【讨论】:

    【解决方案2】:

    使用malloc,不会调用类构造函数。请改用new

    【讨论】: