Rasool
Rasool

Reputation: 286

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. 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.

Upvotes: 0

Views: 2248

Answers (3)

Th30n
Th30n

Reputation: 303

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. The code you posted has allocated the array for 110 integer elements which obviously is not enough. 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.

Upvotes: 1

Sergii Khaperskov
Sergii Khaperskov

Reputation: 441

In your link 1 ≤ N ≤ 100 which means nums array should be able to store up to 100*100=10000 values.

Upvotes: 1

np_complete
np_complete

Reputation: 163

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 . 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. so, your program is correct.

Upvotes: 0

Related Questions