尝试创建一个包含字符串的链表
Trying to make a Linked List that contains strings C++
我目前正在研究一个链表,它将具有包含信息字符串的字符串。我正在使用一个结构体,看起来像这样:
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
不会这样做。
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 如何在 c++ 项目中包含一个包含所有头文件?
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 在使用PyInstaller冻结Python脚本时包含一个C++可执行文件
- 只要我不包含一个标题,重新定义C++关键字合法吗
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 重载运算符主体仅包含一个函数调用
- 一次包含一个 #include 表达式的多个头文件?
- C++:如何创建一个临时对象,包含一个指针 - 常量或非常量,具体取决于上下文
- 如何查找一组类型对是否包含一个元素作为第二个成员
- 仅包含一个 printf 的程序崩溃
- NDK - 包含一个预构建的库,并在 Android 项目中调用本机函数
- 如何为字符串编写正则表达式,其中包含一个数字至少一个数字,并且不包含任何字母
- 如何在Java中包含一个库,该库在C 中具有Java中具有本机绑定(库)的库
- 为什么string.empty()在字符串包含一个值时评估为true
- [C ] NULL确实在内存中也包含一个特定的地址
- 如果QString包含一个数字
- 为什么 C++11 包含一个关于比较空指针的奇怪子句
- 正在(在构造函数中)将其包含一个不良设计的指针传递,如果是的,则解决方案是什么