构造函数中的分段错误

Segmentation fault in the constructor

本文关键字:错误 分段 构造函数      更新时间:2023-10-16

程序可以编译,但在运行时,它会打印"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;