分段错误 - C++阵列



我正在尝试使用以下连接更改某些标签的文本:

connect(ui->styleSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(setStyle(int)));
connect(this, SIGNAL(instrumentChanged(QString)), ui->label_inst_1, SLOT(setText(QString)));
connect(this, SIGNAL(instrumentChanged_2(QString)), ui->label_inst_2, SLOT(setText(QString)));
connect(this, SIGNAL(instrumentChanged_3(QString)), ui->label_inst_3, SLOT(setText(QString)));

我的setStyle槽:

    void SamplerModule::setStyle(int style){
    m_style = style;  
    emit instrumentChanged(m_instruments[m_style][0]);
    emit instrumentChanged_2(m_instruments[m_style][1]);
    emit instrumentChanged_3(m_instruments[m_style][3]);
}

和我的数组(在我的类构造函数中设置)

QString m_instruments[3][3];
m_instruments[0][1] = "Trompette";
m_instruments[0][2] = "Basse";
m_instruments[0][3] = "Piano";
m_instruments[1][1] = "Guitare";
m_instruments[1][2] = "Batterie";
m_instruments[1][3] = "Basse";
m_instruments[2][1] = "Basse";
m_instruments[2][2] = "Batterie";
m_instruments[2][3] = "Guitare";

但是当我尝试运行代码时,由于我的信号使用 m_instruments[x][0] 而出现分段错误。

我真的不明白为什么。我的插槽setStyle有权访问这个阵列,那么为什么会有这个分段错误呢?


细节:

如果我在标头中设置QString m_instruments[3][3];而不是QString m_instruments[][3];,则 seg 错误就会消失。但是,数组在构造函数外部显示为空。

qDebug() << m_instruments[0][0];在构造器中返回"Trompette",但在我的setStyle插槽中返回"!

在代码中,您列出了以下数组:

QString m_instruments[3][3];

此数组的长度为 3x3,这意味着您可以访问 3 列元素,0、1 和 2。在这一行上:

m_instruments[0][3] = "Piano";

您访问元素索引 3,该索引超过数组的末尾,这会导致未定义的行为(在您的情况下会导致 seg 错误)。

这可能不是您的代码的唯一问题,但它肯定是其中之一。

最新更新