Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何初始化QGraphicsItem的二维数组_C++_Arrays_Qt_Segmentation Fault - Fatal编程技术网

C++ 如何初始化QGraphicsItem的二维数组

C++ 如何初始化QGraphicsItem的二维数组,c++,arrays,qt,segmentation-fault,C++,Arrays,Qt,Segmentation Fault,我使用Qt来实现一些gui功能,我继承了qgraphicscene来实现我自己的一些方法,我做的其中一件事就是创建一个QGraphicsItem列表,特别是我创建的一个对象的二维数组,它插入了QGraphicsItem MatrixButton **buttons; 然后,当我用这个方法从QGraphicscene初始化列表时,我得到了一个分段错误 void MatrixScene::initScene() { this->setSceneRect(0, 0, this->

我使用Qt来实现一些gui功能,我继承了qgraphicscene来实现我自己的一些方法,我做的其中一件事就是创建一个QGraphicsItem列表,特别是我创建的一个对象的二维数组,它插入了QGraphicsItem

MatrixButton **buttons;
然后,当我用这个方法从QGraphicscene初始化列表时,我得到了一个分段错误

void MatrixScene::initScene()
{
    this->setSceneRect(0, 0, this->width*BUTTON_SIZE, this->height*BUTTON_SIZE);
    this->currentFrameIndex = 0;
    this->color = Qt::red;
    this->buttons = new MatrixButton*[this->height];
    for (int i = 0; i < this->height; i++){
        this->buttons[i] = new MatrixButton[this->width];
    }
    for (int x = 0; x < this->width; x++){
        for (int y = 0; y < this->height; y++){
            this->buttons[x][y].setPos(x*BUTTON_SIZE, y*BUTTON_SIZE); //SEGMENTATION FAULT!!!
            this->addItem(&this->buttons[x][y]);
        }
    }
    this->update();
}

具体来说,根据调试器,当ax=640和ay=0时会发生故障。我不明白在这种情况下是什么导致分段错误。

您的问题是您使用x作为行的索引,使用y作为列的索引,但边界条件正好相反

因此,请将代码修改为:

for (int x = 0; x < this->height; x++){
        for (int y = 0; y < this->width; y++){
            this->buttons[x][y].setPos(x*BUTTON_SIZE, y*BUTTON_SIZE);        
            this->addItem(&this->buttons[x][y]);
        }
    }
for(intx=0;xheight;x++){
对于(int y=0;ywidth;y++){
此->按钮[x][y]。设置位置(x*按钮大小,y*按钮大小);
此->添加项(&此->按钮[x][y]);
}
}

2件事:这个->宽度有什么价值?第二:我建议您使用
QVector
而不是
MatrixButton**
。请参见此处(std::vector也适用于QVector)@Hayt此->宽度为64,此->高度为32。出于好奇,我仍然想知道是什么导致了分割错误。这是什么类型的->宽度?浮点?你确定你的循环是正确的吗?当您选中
xwidth
x时,x应在63处停止。或者在“真实代码”中是否有
No,我确信永远不会有越界错误,因为x从0增加到63,并且
BUTTON_SIZE
是20,但这应该不会对结果产生影响。
for (int x = 0; x < this->height; x++){
        for (int y = 0; y < this->width; y++){
            this->buttons[x][y].setPos(x*BUTTON_SIZE, y*BUTTON_SIZE);        
            this->addItem(&this->buttons[x][y]);
        }
    }