繁体   English   中英

为什么我会遇到访问冲突的运行时错误?

[英]Why do I get access violation run-time error?

我想在二维数组上对角迭代。 我使用[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倍的值。

无论如何:站点状态1 <= N <= 100 ,这意味着你需要的最大可能数组是max(N*N) ,即10,000个整数。 您发布的代码已经为110个整数元素分配了数组,这显然是不够的。 在读取第一个for循环中的输入数字期间可能会发生访问冲突,因为i转到n*n ,这可能大于数组的大小。

首先是我的朋友,你在使用哪个编译器? 如果是borland的turbo,那么你可能想切换到另一个,因为这是我经历过的常见错误。 你的代码似乎是正确的,通过在Code :: Blocks中执行相同的代码(copy-pasting),我得到了你提到的输出。 所以,你的程序是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM