如何解决这个2D数组如何访问分配的索引?
数组如何访问大于其宽度的索引处的值。 我认为当您超过大小限制时,它将引发段错误。
#include <iostream>
int main(){
const int len = 3;
const int wid = 3;
int arr[len][wid];
int count = 1;
// assigns array to numbers 1 - 9
for(int i =0;i < len;i++){
for(int j =0;j< wid;j++){
arr[i][j] = count++;
}
}
int index = 0;
// prints out the array
while(index < 9){
std::cout << arr[0][index++] << " "; // how is it accessing space that wasn't allocated? index++
}
std::cout << std::endl;
}
解决方法
std :: cout
即使项目总数相同(9),也不能只从2D数组更改为1D数组。
看起来您的目的只是打印输出数组,您可能只想像输入时那样遍历2D数组索引:
所以代替这个:
// prints out the array
while(index < 9){
std::cout << arr[0][index++] << " "; // out of bound access - undefined behaviour (crash or worse)
}
执行此操作:
for (int i = 0; i < len; i++)
{
for (int j = 0; j < wid; j++)
{
cout << arr[i][j] << ' ';
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。