Random program crashes

I'm trying to figure out why this program crashes sometimes but then runs successfully other times. The program initializes a 2d char array in a grid pattern and then prints it out. It seems to crash every other time I run it. Anyone have any ideas to what might be wrong with it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
void resetGrid(char grid[][51]);
void addBox(char grid[][51], int x, int y, int width, int height);
void printGrid(char grid[][51]);

int main()
{
	char grid[21][51];
	resetGrid(grid);
	printGrid(grid);
}

void resetGrid(char grid[][51])
{
	for(int y=0;y<21;y++)
	{
		for(int x=0;x<51;x++)
		{
			if(x%5==0 && y%5==0)
				grid[x][y]='+';
			else if(x%5!=0 && y%5==0)
				grid[x][y]='-';
			else if(x%5==0 && y%5!=0)
				grid[x][y]='|';
			else
				grid[x][y]=' ';
		}
	}
}

void printGrid(char grid[][51])
{
	for(int y=0;y<21;y++)
	{
		for(int x=0;x<51;x++)
		{
			printf("%c",grid[x][y]);
		}
		printf("\n");
	}
}
Last edited on
@tylradm5

You have the x and y mixed up in the for loops of the functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void resetGrid(char grid[][51])
{
	for(int y=0;y<21;y++)// The 'y' in the array is 51,
	{
		for(int x=0;x<51;x++)//  and 'x' to 21
		{
			if(x%5==0 && y%5==0)
				grid[x][y]='+';// The 'y' in the array is 51, and 'x' to 21
			else if(x%5!=0 && y%5==0)
				grid[x][y]='-';
			else if(x%5==0 && y%5!=0)
				grid[x][y]='|';
			else
				grid[x][y]=' ';
		}
	}
}


Change them around in both functions, and it works perfectly
Last edited on
You're right, it does! Thanks!
Topic archived. No new replies allowed.