Array Segmentation Fault char vs int

Hi All, Little bit of a weird thing happening here, Curious why this works:

1
2
3
4
5
6
7
8
9
10
11
    char GameBoard[ROWS][COLM];
    
    for (int i =0; i <= ROWS; i++)
    {
        for(int j = 0; j <= COLM; j++)
        {
            GameBoard[i][j] = 'o'; 
        }
    }



and this gives a segmentation fault :

1
2
3
4
5
6
7
8
9
10
    int GameBoard[ROWS][COLM];
    
    for (int i =0; i <= ROWS; i++)
    {
        for(int j = 0; j <= COLM; j++)
        {
            GameBoard[i][j] = 1; 
        }
    }


I am totally stumped. They both should work, should they not?
Your code has undefined behavior by default, and the symptom of it can be revealed differently in different situations.

The code should be :
1
2
3
4
5
6
7
for (int i =0; i < ROWS; i++)
    {
        for(int j = 0; j < COLM; j++)
        {
            GameBoard[i][j] = 1; 
        }
    }


Note that array subscript starts at 0, and finish at size - 1.
Okay, I understand that it should have been < instead of <= (Was trying to get it to print the amount I desired.)

I think I just had a bit of a brain shortage.

I had forgotten that defining an array of size 3 means you get an array of positions
0,1,2
(I had set size to 2, thinking that I would get an array of 0,1,2)

So following that trend I setup my for loops incorrectly and ended up with seg faults.

Silly how the simple things elude you when you haven't programmed in awhile!

Thank you.

(Though still curious how a char array of size 2 can fill position 3 without seg fault)
(Though still curious how a char array of size 2 can fill position 3 without seg fault)

You know what is right or wrong. Do not try to commit undefined behavior.
I think that you need to share you output expected to have more idea or the full code.
thanks.
Topic archived. No new replies allowed.