首页 > 解决方案 > 在链表中添加字符串的简单方法

问题描述

我有一个代码来实现链表它工作正常。我想在链接列表中包含一个字符串,但是当我添加字符串时,我得到一个运行时错误,当程序到达这一行时崩溃:

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++linked-list

解决方案


你混合CC++使用任何一种。而不是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?


推荐阅读