分段错误 - C++阵列
Segmentation fault - C++ array
我正在尝试使用以下连接更改某些标签的文本:
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 错误)。
这可能不是您的代码的唯一问题,但它肯定是其中之一。
相关文章:
- OpenMP阵列性能较差
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- 位阵列上的快速AND运算
- 阵列必须使用大括号封闭的初始器进行初始化
- 没有从阵列<float>到阵列<int>的可行转换
- C++动态安全 2D 交错阵列
- 将平面阵列重塑为复杂的特征类型
- 如何使用英特尔 PIN 捕获阵列的所有负载?
- 为什么我能够为阵列分配比计算机实际拥有的内存更多的内存
- 库特<<恩德尔;不适用于打印 2D 阵列
- 数组类 阵列的打印输出
- 从较小的阵列到较大的阵列的元素级转换
- 仅在大型阵列上出现合并排序分段错误
- 从阵列C++中删除重复项
- 阵列的大小在C++中是否灵活?
- 反转阵列中的正序列
- 具有可变尺寸的 C++ 2D 阵列
- 二维阵列的动态分配
- 重新增长阵列时出错:写入时缓冲区溢出