[英]Why do I get access violation run-time error?
I want to iterate diagonally over a two dimensional array. 我想在二维数组上对角迭代。 I use a normal array with [N*N]
size instead of using an [N][N]
array. 我使用[N*N]
大小的普通数组而不是[N][N]
数组。 After that, I produce the indexes. 之后,我生成索引。 This is the array I want to print (for example) 这是我要打印的数组(例如)
1 3 6 10
2 5 9 13
4 8 12 15
7 11 14 16
the result should be like this: 结果应该是这样的:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
I've done with the following code: 我已经完成了以下代码:
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;
}
I think it should work, but I don't know why I get access violation run-time error. 我认为它应该工作,但我不知道为什么我得到访问冲突运行时错误。 Thanks. 谢谢。
在您的链接1 ≤ N ≤ 100
这意味着nums
阵列应该能够存储多达100 * 100 = 10000倍的值。
Anyways: the site states 1 <= N <= 100 which means the largest possible array you will need is max(N*N)
which is 10,000 integers. 无论如何:站点状态1 <= N <= 100 ,这意味着你需要的最大可能数组是max(N*N)
,即10,000个整数。 The code you posted has allocated the array for 110 integer elements which obviously is not enough. 您发布的代码已经为110个整数元素分配了数组,这显然是不够的。 The access violation might be happening during the reading of input numbers in the first for loop because i
goes to n*n
which might be larger than the size of your array. 在读取第一个for循环中的输入数字期间可能会发生访问冲突,因为i
转到n*n
,这可能大于数组的大小。
first of all my friend, which compiler are you using? 首先是我的朋友,你在使用哪个编译器? if borland's turbo , then you may want to switch over to another one because this is a common error in that as i have experienced . 如果是borland的turbo,那么你可能想切换到另一个,因为这是我经历过的常见错误。 your code seems to be correct and by executing the same code(copy-pasting) in Code::Blocks , I got the output as you have mentioned. 你的代码似乎是正确的,通过在Code :: Blocks中执行相同的代码(copy-pasting),我得到了你提到的输出。 so, your program is correct. 所以,你的程序是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.