为什么 g++ 在将节点指向数据字符时返回'Segmentation fault'错误?
Why is g++ returning a 'Segmentation fault' error when I point a node to a char of data?
我有一个程序,在编译后返回一个错误,然后在g++中运行它。我知道,因为当我在Visual Studio中测试这段代码时,当我试图设置一个新的节点数据指针等于什么东西时,这个错误就会发生。更具体地说,当我试图设置n->data = ch;
Visual Studio中断(停止)在那行代码。作为上下文,以下是我的头文件的一部分(末尾为n->data = ch;
):
#include <ostream>
class LinkedList
{
public:
LinkedList();
~LinkedList();
void add(char ch);
private:
struct node
{
node();
char data;
node * next;
};
node * head;
node * curr;
node * prev;
};
LinkedList::LinkedList() : head(nullptr), curr(nullptr), prev(nullptr);
LinkedList::node::node() : data(' '), next(nullptr);
LinkedList::~LinkedList()
{
if (!head) // head is null and so list is empty
{
return; //nothing to delete
}
for(curr = head; head; /* head isn't NULL*/ delete curr /*delete first element*/)
{
curr = head; // set curr to head of list
head = curr->next; // move head over to next element (or make it null)
}
}
void LinkedList::add(char ch)
{
node * n = nullptr;
n->next = nullptr; //my compiler doesn't like this
n->data = ch; // or this
//irrelevant code after this.
}
我希望我能给你们更多的背景,但我不知道为什么这不起作用。即使它确实与C字符串有关,我不知道该怎么做来解决这个问题。
void LinkedList::add(char ch) { node * n = nullptr; // ## n->next = nullptr; //my compiler doesn't like this n->data = ch; // or this ...
在第一行(标记为##
)中,您定义了一个指向node
的指针,并将其初始化为nullptr
,因此该指针实际上指向"nothing"。
因此,您不能使用该指针为node
数据结构字段(n->next
和n->data
)设置值,因为它在前一行中没有指向任何值。
您可以做的是创建一个新的node
的实例(例如使用 new
),然后准备该实例的字段,使用n->next
和n->data
。
作为你的代码
node * n = nullptr;
表示将空指针赋给n
然后通过
n->next = nullptr;
这就导致了分割故障。
使用
解决node * n = new node();
n->next = nullptr;
n->data = ch;
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 创建一个简单的类及其变量和函数不断返回" segmentation fault (core dumped)"、C++
- 为什么 g++ 在将节点指向数据字符时返回'Segmentation fault'错误?