尝试创建一个包含字符串的链表

Trying to make a Linked List that contains strings C++

本文关键字:包含 一个 字符串 链表 创建      更新时间:2023-10-16

我目前正在研究一个链表,它将具有包含信息字符串的字符串。我正在使用一个结构体,看起来像这样:

struct symbolTable
{
    string lexeme;
    string kind;
    string type;
    int offSet;
    symbolTable *nextSymbol;
    symbolTable *nextTable;
};

插入函数看起来有点像这样:

void MPParser::insertToSymbolTable(string identifier, string type, string kind)
{
    tempOffset++;
    symbolTable *tempNode;
    tempNode = (symbolTable*)malloc(sizeof(symbolTable));
    tempNode->kind = kind; //Run Time error Here..
    tempNode->type = type;
    tempNode->lexeme = identifier;
    tempNode->offSet = tempOffset;
    tempNode->nextTable = NULL;
    tempNode->nextSymbol = root;
    root = tempNode;
}

程序编译,然后当我试图运行并插入到链表中时,我得到这个错误:

Unhandled exception at 0x5A6810D0 (msvcr110d.dll) in mpcompiler.exe: 0xC0000005: Access   violation writing location 0xCDCDCDCD.

在指针中将一个字符串赋值给另一个字符串的正确方法是什么?还是我做错了什么?任何帮助将不胜感激!

谢谢!

使用new代替malloc(),这样字符串对象就可以正确构造:

tempNode = new symbolTable;

然后在需要释放节点时使用delete:

delete node;

尝试用

替换你的代码
void MPParser::insertToSymbolTable(string identifier, string type, string kind)
{
    tempOffset++;
    symbolTable *tempNode;
    tempNode = new symbolTable;
    tempNode->kind = kind; //Run Time error Here..
    tempNode->type = type;
    tempNode->lexeme = identifier;
    tempNode->offSet = tempOffset;
    tempNode->nextTable = NULL;
    tempNode->nextSymbol = root;
    root = tempNode;
}

Access Violation表示您正在写入未分配的内存。在c++中千万不要使用malloc,因为它不调用constructors,总是使用new来创建动态对象,使用delete来释放它们。

我在gcc 4.5.3下做了一个非常简单的测试:

#include <iostream>
#include <string>
struct A
{
  std::string a;
};
int main()
{
   A* ptr = new A;
   ptr->a = "hello";
   std::cout << ptr->a << std::endl;
   //A aStruct;
   A* ptr2 = (A*)malloc(sizeof(A));
   //ptr2 = &aStruct;
   ptr2->a = "hello again";   //simulate what you have done in your code
   std::cout << ptr2->a << std::endl;
   std::cin.get();
};

这将导致核心转储,因为ptr2试图访问原始内存。但是,如果我取消注释:

//A aStruct;
//ptr2 = &aStruct;

然后按预期工作。因此,您应该使用new而不是malloc。原因是new将调用类的构造函数来初始化分配的内存块,但是malloc不会这样做。

相关文章: