Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

access violation writing to 2d array in c

I’m trying to initialise a 2d array, and for some reason I’m getting an exception whenever I try to enter a value into the array.

I’m passing it to the function in a struct, if that makes a difference?

Here’s the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#define board_size 10

typedef struct {
    int b[board_size][board_size];
} board;

board dead_state();     // initialise a dead board state

void main() {
    board test_board = dead_state();

    for (int i = 0; i < board_size - 1; i++) {
        for (int j = 0; j < board_size - 1; i++) {
            test_board.b[i][j] = 0;
        }
    }
}

board dead_state() {
    // generate the matrix, set all values to 0, return
    board deadboard;

    for (int i = 0; i < board_size - 1; i++) {
        for (int j = 0; j < board_size - 1; i++) {
            deadboard.b[i][j] = 0;
        }
    }

    return deadboard;
}

edit: problem solved, thanks to hyde’s comment: i am blind and cannot see, apparently.

>Solution :

You have what looks like a typo.

    for (int i = 0; i < board_size - 1; i++) {
        for (int j = 0; j < board_size - 1; i++) {
            test_board.b[i][j] = 0;
        }
    }

Both loops increment i, which means i goes out of bounds. You likely meant for the inner loop to increment j, but I don’t know why you’re only incrementing i and j up to 8, instead of 9.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading