c++ - 在链表中添加字符串的简单方法
问题描述
我有一个代码来实现链表它工作正常。我想在链接列表中包含一个字符串,但是当我添加字符串时,我得到一个运行时错误,当程序到达这一行时崩溃:
new_node->name = "hello";
完整代码:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct list_item
{
int key;
int value;
string name;
list_item *next;
};
struct list
{
struct list_item *first;
};
int main()
{
//Just one head is needed, you can also create this
// on the stack just write:
//list head;
//head.first = NULL;
list *head = (list*)malloc(sizeof(list));
list_item *new_node = NULL;
head->first = NULL;
for(int i = 0; i < 10; i++)
{
//allocate memory for new_node
new_node = (list_item*)malloc(sizeof(list_item));
//adding the values
new_node->key = i;
new_node->name = "hello";
new_node->value = 10 + i;
//if the list is empty, the element you are inserting
//doesn't have a next element
new_node->next = head->first;
//point first to new_node. This will result in a LIFO
//(Last in First out) behaviour. You can see that when you
//compile
head->first = new_node;
}
//print the list
list_item *travel;
travel = head->first;
while(travel != NULL)
{
cout << travel->value << endl;
cout << travel->name << endl;
travel = travel->next;
}
//here it doesn't matter, but in general you should also make
//sure to free the elements
return 0;
}
谁能帮助我如何在 C++ 中以正确的方式包含一个字符串?
解决方案
你混合C
并C++
使用任何一种。而不是malloc
用来new
分配内存。
只需使用
new_node = new(list_item);
代替
new_node = (list_item*)malloc(sizeof(list_item));
最后通过调用释放它delete
不要使用malloc
,因为它不会初始化内存。要检查只是运行g++ -g -Wall -fdump-tree-gimple test.cpp
并打开vim test.cpp.004t.gimple
并找到该malloc()
行,它说
new_node = malloc (16); /* allocated using malloc i.e not initialized */
D.21870 = &new_node->name; /* base address of string data type 'name' */
std::basic_string<char>::operator= (D.21870, "hello"); /* it causes the seg. fault */
要获得更多信息,请在什么情况下使用 malloc 与 new?
推荐阅读
- javascript - Angular 8 使用带有异步管道的 ngIf 来显示和隐藏 HTML 元素
- python-3.x - Python dataframe with value 'NA' not fetching
- reactjs - Access to outer react component from referenced component
- apache-spark - Replace cell value according to bin value in dataframe
- google-sheets - How to make select with variable using Google Sheets
- c# - 用 C# 生成的 Excel 文件损坏(ExcelExportEngine & IExportEngine)
- html - 元素不在视口底部
- sql - 如何提高sql server中的while循环插入性能?
- bash - 带有特定文本的多行 grep
- revit-api - REVIT 将地板草图转移到家庭中的空隙挤压