我想对角迭代一个二维数组。我使用 [N*N]
大小的普通数组,而不是使用 [N][N]
数组。之后,我生成索引。
这是我要打印的数组(例如)
1 3 6 10
2 5 9 13
4 8 12 15
7 11 14 16
结果应该是这样的:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
我已经完成了以下代码:
int n, temp[2], nums[100 + 10];
cin >> n;
for (int i = 0; i < n * n; i++)
cin >> nums[i];
temp[0] = temp[1] = 0;
for (int i = 0, cnt = 0; i < n; i++, cnt += 5) {
temp[1] = temp[0];
for (int j = 0; j <= i; j++) {
cout << nums[temp[1]] << " ";
temp[1] -= n - 1;
}
temp[0] += n;
}
temp[0] -= n - 1;
for (int i = n - 2, cnt = temp[0]; i >= 0; i--, cnt -= 5) {
temp[1] = temp[0];
for (int j = 0; j <= i; j++) {
cout << nums[temp[1]] << " ";
temp[1] -= n - 1;
}
temp[0] += 1;
}
我认为它应该可以工作,但我不知道为什么会出现访问冲突运行时错误。 谢谢。
最佳答案
在您的链接中 1 ≤ N ≤ 100
这意味着 nums
数组应该能够存储多达 100*100=10000 个值。
关于c++ - 为什么会出现访问冲突运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21801211/