构造函数中的分段错误
Segmentation fault in the constructor
程序可以编译,但在运行时,它会打印"asd12",然后是"asd45",然后是"分段错误(核心转储)"。它不打印"asd67"。有人可以帮助我吗?
struct node{
int a[3];
int b;
int c;
node* parent;
node(){
b=0;
parent=NULL;
}
};
int main(){
node* x;
node* y;
cout << "asd12"<< endl;
x->a[0]=1;x->a[1]=1;x->a[2]=1;
cout << "asd45"<< endl;
y->a[0]=1;y->a[1]=1;y->a[2]=1;
cout << "asd67"<< endl;
return 0;
}
您已将 x 和 y 声明为指向结构节点对象的指针,但未创建对象。
最简单的解决方案是将您的声明从
node* x;
node* y;
自:
node x;
node y;
这将创建自动节点变量,并允许您访问数组元素,如下所示:
x.a[0] = 1;
您也可以使用
node* x = new node;
node* y = new node;
// access vars using pointer syntax
x->a[0] = 1;
// when finished with x and y, delete the created objects
delete x;
delete y;
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)