C - Chomp questions - c

I'm trying to create the game Chomp. I am halfway through but pretty stuck.
The game will have 5 different functions. Pointers and structs are not allowed.
a) initialize() Initialize every position in the matrix to 'O'. No parameters or return value.
b) print_board() Prints the matrix. No parameters or return value.
c) get_move() Scan a move from the player (row and col) and "return" it with an array. Parameters: Information about whos turn it is (Player 1 or Player 2), and an array with two elements where the move coordinates will be stored. No return value.
d) check_move() Controls if a move is legal (not outside the matrix and not a position that has already been eaten). Parameters: The move that is going to be checked (row and col). Return value: Result of the control. <------ ???????
e) update_board() Updates the matrix. Parameters: The new move (row and col). No return value.
This is how far I have come and I am stuck at the check_move() function. I don't understand what I am going to return from that function.
#include <stdio.h>
int height = 4;
int width = 10;
char matrix[4][10];
void initialize()
{
for(int row = 0; row < height; row++)
for(int col = 0; col < width; col++)
matrix[row][col] = 'O';
}
void print_board()
{
for(int row = 0; row < height; row++)
{
for(int col = 0; col < width; col++)
{
printf("%c", matrix[row][col]);
}
printf("\n");
}
printf("\n");
}
void get_move(int player, int input[])
{
printf("Player %d, make your move: ", player);
scanf("%d %d", &input[0], &input[1]);
}
int check_move(int position[])
{
int row = position[0];
int col = position[1];
if(row <= height && col <= width)
{
for(row; row <= height; row++)
{
for(col; col <= width; col++)
{
if(matrix[row][col] == ' ');
printf("Invalid move! \n");
}
}
}
}
void update_board(int x, int y)
{
for(int xi = x; xi <= 10; ++xi)
{
for(int yi = y; yi <= 10; ++yi)
matrix[xi-1][yi-1] = ' ';
}
}
int main(void)
{
int player = 1;
int position[2];
initialize();
print_board();
get_move(player, position);
check_move(position);
update_board(position[0], position[1]);
print_board();
getchar();
getchar();
getchar();
return 0;
}

You should return a value from check_move, because it is prototyped that way, I assume you want to use the exit status somewhere? :
int check_move(int position[])
and you have an unnecessary ; at the end of your if:
int check_move(int position[])
{
int row = position[0];
int col = position[1];
int status = 1;
if(row <= height && col <= width)
{
for(row; row <= height; row++)
{
for(col; col <= width; col++)
{
if(matrix[row][col] == ' ') //removed ";" from end of line, otherwise,
{ //printf will always be called
printf("Invalid move! \n");
return 0;
}//also added brackets to force return if error (only need one error to return)
}
}
}
return status; //added return status
}
So, now in the main, you would do something like this to call check_move():
int main(void)
{
int player = 1;
int position[2];
initialize();
print_board();
get_move(player, position);
while(check_move(position) != 1)
{
printf("Try again!\n\n");
print_board();
get_move(player, position);
}
update_board(position[0], position[1]);
print_board();
getchar();
getchar();
getchar();
return 0;
}

Related

How to undo a stack when the struct contains a char ** variable?

This code below is something like a candy crush game, where you pop similar letters in a cluster, then they'll disappear and you score. On main, I tried to play it one step ahead and then undo it, and it works since the score managed to undo (from 0 to some score then back to 0 again). However, I just can't figure out why the game board isn't updated?
typedef struct {
int rs;
int cs;
char **board;
int score;
} Instance;
with random letters (a, b ,c or d)
extern Game *create(int nrows, int ncols) {
if (nrows > MAX_ROWS || ncols > MAX_COLS) {
return NULL;
}
Game *b;
b->top = 0;
b->stack[b->top].rs = nrows;
b->stack[b->top].cs = ncols;
b->stack[b->top].board = malloc(sizeof(char *) * nrows);
for (int row = 0; row < nrows; row++) {
b->stack[b->top].board[row] = malloc(sizeof(char) * ncols);
}
srand(time(0));
for (int row = 0; row < nrows; row++) {
for (int column = 0; column < ncols; column++) {
int random = rand() % 4;
if (random == 0) {
b->stack[b->top].board[row][column] = A;
} else if (random == 1) {
b->stack[b->top].board[row][column] = B;
} else if (random == 2) {
b->stack[b->top].board[row][column] = C;
} else {
b->stack[b->top].board[row][column] = D;
}
}
}
return b;
}
// Display the current matrix
extern void display(Game *b) {
/** Prints top border **/
printf(" +-");
for (int top = 0; top < b->stack[b->top].cs; top++) {
printf("--");
}
printf("+\n");
/** Prints the board **/
for (int row = 0; row < b->stack[b->top].rs; row++) {
if (row < 10) {
printf("0%d | ", row);
} else {
printf("%d | ", row);
}
for (int column = 0; column < b->stack[b->top].cs; column++) {
printf("%c ", b->stack[b->top].board[row][column]);
}
printf("|\n");
}
/** Prints bottom border **/
printf(" +-");
for (int bot = 0; bot < b->stack[b->top].cs; bot++) {
printf("--");
}
printf("+\n");
/** Prints vertical column indices **/
printf(" ");
for (int tens = 0; tens < b->stack[b->top].cs; tens++) {
printf("%d ", tens/10);
}
printf("\n");
printf(" ");
int count = 0;
for (int ones = 0; ones < b->stack[b->top].cs; ones++) {
if (count > 9) {
count = 0;
}
printf("%d ", count);
count++;
}
}
extern int select(Game *b, int r, int c) {
char colour = b->stack[b->top].board[r][c];
int n = recursive_helper(b, r, c);
if (n == 1) {
b->stack[b->top].board[r][c] = colour;
return 0;
}
b->stack[b->top].score += n*(n-1);
return n;
}
int main() {
Game *b = create(5, 10);
display(b);
printf("\n");
printf("%d", bp_score(b));
printf("\n");
select(b, 2, 2);
display(b);
printf("\n");
printf("%d", bp_score(b));
printf("\n");
b->top--;
display(b);
printf("\n");
printf("%d", bp_score(b));
printf("\n");
}
As pointed in the comments, your create function doesn't instantiate a Game struct, you need b = malloc(sizeof(Game));
Another error is that your mallocs use sizeof(int*) and sizeof(int) instead of sizeof(char*) and sizeof(char).
Other than that, your problem comes from the fact that b->stack[b->top+1] = b->stack[b->top]; copies a structure, but the board is a pointer and points to the same object! You only have one char** pointer and a single board in memory.
Thus, when you do b->top-- while you do access another struct, it still points to the same fully updated board.
You need to create a function Instance CopyInstance(Instance src) that creates a new board in the new struct and then copies each cell from the source board in the new one. That way each Instance will point to a different board!

Shortest path to any point in a maze

So I have to scan a maze number of rows and columns for a file, bit I got that part.
File have a form like this
3
4
....
.#.#
....
Where the first number is a number of rows and the second is the number of columns. Character '#' is a wall and I can't go there but I can go through '.'
Now I have to, using structures and pointers, find a shortest path to any point in a maze. Example structure is in my code (Cell).
I have no idea how to do this. I've created a array 'visited' to track which cell I've been to and function to check if a point is valid.
Somehow I have to point to other points in NORTH, WEST, EAST, SOUTH directions.
#include "stdafx.h"
#include "stdlib.h"
//Starting point
#define START_X 0
#define START_Y 0
//example structure I have to use
struct Cell
{
struct Cell *north;
struct Cell *east;
struct Cell *south;
struct Cell *west;
char value;
int distance;
};
//function that prints a maze
void printMap(char **charMaze, int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf_s("%c", charMaze[i][j]);
}
printf_s("\n");
}
}
// functions that check if a point is valid
bool isValid(int x, int y, int row, int col)
{
if (x < row && y < col && x >= 0 && y >= 0)
return true;
return false;
}
bool isSafe(char **charMaze, int **visited, int x, int y)
{
if (charMaze[x][y] == '#' || visited[x][y]==true)
return false;
return true;
}
//My attempt at solving this
int BFS(char **maze,int END_X, int END_Y,int row, int col, bool **visited)
{
isValid(END_X, END_Y, row, col);
}
int main()
{
FILE *map;
int row, col;
// I open a file with a maze
fopen_s(&map, "test1.txt", "r");
// I scan a row number and column number
fscanf_s(map, "%d", &row);
fscanf_s(map, "\n%d\n", &col);
char** charMaze;
charMaze = (char**)malloc(row * sizeof(char*));
for (int i = 0; i < row; i++)
charMaze[i] =(char*)malloc(col * sizeof(char));
bool** visited;
visited = (bool**)malloc(row * sizeof(bool*));
for (int i = 0; i < row; i++)
visited[i] = (bool*)malloc(col * sizeof(bool));
//set staring point as true and other points as false
visited[START_X][START_Y] = true;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
visited[i][j] = false;
}
}
// I scan a maze and I put it in a array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
fscanf_s(map, "%c", &charMaze[i][j],1);
}
fscanf_s(map, "\n");
}
fclose(map);
//printMap(charMaze, row, col);
return 0;
}
You could use the Dijkstra algorithm to find the shortest path.
As result, suppose you have to return a path from the starting point to every dot in the maze.
You have here an implementation of the Dijkstra algorithm.
You would need to adapt it your maze map.
You could use a matrix of structs where each struct contains the x,y coordinate of the previous node, the distance to the starting node, and the flag done.
Edit
If fact you don’t even need to implement the Dijkstra algorithm. A simple flooding algorithm will do because the weight of all vertex of the graph is one.
Here is how I would do it.
#include <stdbool.h>
#include <stdlib.h>
enum State { Wall, Unvisited, WaveBorder, NewWaveBorder, Done };
// define the structure holding coordinates of previous cell in path and state
typedef struct Cell {
int i,j; // coordinates of predecessor in path
enum State state;
} Cell;
// visit cell (vi,vj) from neighbor cell (i,j)
void visitCell(Cell **m, int vi, int vj, int i, int j) {
if m[vi][vj].state == Unvisited {
m[vi][vj].state = NewWaveBorder;
m[vi][vj].i = i;
m[vi][vj].j = j;
}
}
Cell** findShortestPath(char **maze, int row, int col, int iStart, int jStart) {
Cell **m = malloc(sizeof(Cell*)*row);
for (int i = 0; i < row; i++)
m[i] = malloc(sizeof(Cell)*col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (maze[i][j] == '.') {
m[i][j].state = Unvisited;
m[i][j].i = m[i][j].j = -1;
} else {
m[i][j].state = Wall;
m[i][j].i = m[i][j].j = -2;
}
m[iStart][jStart].state = WaveBorder;
bool done = false;
while (!done) {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
if (m[i][j].state != waveBorder)
continue;
if (i > 0)
visitCell(m, i-1, j, i, j);
if (j > 0)
visitCell(m, i, j-1, i, j);
if (i < row)
visitCell(m, i+1, j, i, j);
if (j < col)
visitCell(m, i, j+1, i, j);
m[i][j].state = Done;
}
done = true;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (m[i][j].state == Unvisited)
done = false;
else if (m[i][j].state == NewWaveBorder)
m[i][j].state == WaveBorder;
}
return m;
}
The path from cell (i,j) is stored in the matrix of Cell structures. Each cell has the coordinates of the predecessor in the path toward (iStart, jStart). The cell (iStart,jStart) will have (-1,-1) as predecessor in the path. Walls will have (-2,-2) as predecessors.
Okay I did something like this. But it doesn't work for some reason.
#include "stdafx.h"
#include "stdlib.h"
//Starting point
#define START_X 0
#define START_Y 0
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
//example structure I have to use
struct Cell
{
struct Cell *north;
struct Cell *east;
struct Cell *south;
struct Cell *west;
char value;
int distance;
};
//function that prints a maze
void printMap(char **charMaze, int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf_s("%c", charMaze[i][j]);
}
printf_s("\n");
}
}
void printMap2(int **intMaze, int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf_s("%d", intMaze[i][j]);
}
printf_s("\n");
}
}
// functions that check if a point is valid
bool isValid(int x, int y, int row, int col)
{
if (x < row && y < col && x >= 0 && y >= 0)
{
printf("Dobry punkt");
return true;
}
else
{
printf("Nieprawidlowy");
}
return false;
}
bool isSafe(char **charMaze, int **visited, int x, int y)
{
//char wall = '#';
//char character = charMaze[x][y];
if (charMaze[x][y] =='#' || visited[x][y])
{
printf("unsafe");
return false;
}
else
{
printf("safe");
}
return true;
}
bool canGo(Cell *cell, int d)
{
if (cell == NULL)
{
return 0;
}
if (cell->value == '#')
return 0;
if (cell->value == '.')
return 1;
if (cell->distance > d)
return 1;
return 0;
}
void findShortestPath(char **maze, int start_X, int start__Y, int i, int j, int row, int col, int **visited, int minDist, int dist)
{
if (j = start__Y && i == start_X)
{
minDist = MIN(dist, minDist);
return;
}
visited[start_X][start__Y] = 1;
//bottom
if (isValid(start_X + 1, start__Y, row, col) && isSafe(maze, visited, start_X + 1, start__Y))
findShortestPath(maze, start_X + 1, start__Y, i, j, row, col, visited, minDist, dist + 1);
//right
if (isValid(start_X, start__Y + 1, row, col) && isSafe(maze, visited, start_X, start__Y + 1))
findShortestPath(maze, start_X, start__Y + 1, i, j, row, col, visited, minDist, dist + 1);
//top
if (isValid(start_X - 1, start__Y, row, col) && isSafe(maze, visited, start_X + 1, start__Y))
findShortestPath(maze, start_X + 1, start__Y, i, j, row, col, visited, minDist, dist + 1);
//left
if (isValid(start_X, start__Y - 1, row, col) && isSafe(maze, visited, start_X, start__Y - 1))
findShortestPath(maze, start_X, start__Y - 1, i, j, row, col, visited, minDist, dist + 1);
visited[start_X, start__Y] = 0;
}
int main()
{
FILE *map;
int start_X = 0;
int start_Y = 0;
int row, col;
struct Cell cell;
// I open a file with a maze
fopen_s(&map, "test1.txt", "r");
// I scan a row number and column number
fscanf_s(map, "%d", &row);
fscanf_s(map, "\n%d\n", &col);
char** charMaze;
charMaze = (char**)malloc(row * sizeof(char*));
for (int i = 0; i < row; i++)
charMaze[i] = (char*)malloc(col * sizeof(char));
int** visited;
visited = (int**)malloc(row * sizeof(int*));
for (int i = 0; i < row; i++)
visited[i] = (int*)malloc(col * sizeof(int));
memset(visited, 0, sizeof visited);
int minDist = INT_MAX;
// I scan a maze and I put it in a array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
fscanf_s(map, "%c", &charMaze[i][j], 1);
}
fscanf_s(map, "\n");
}
findShortestPath(charMaze, start_X, start_Y, 2, 3, row, col, visited, minDist, 0);
if (minDist != INT_MAX)
{
printf("Najkrotsza droga z poczatku do konca to %d", minDist);
}
else
{
printf("Can't get to the point");
}
printMap(charMaze, row, col);
fclose(map);
return 0;
}

Abort Trap Error: 6 - where is it coming from? - Sudoku solver

Have a sudoku solver method that check row/col location for solution and backtracks after testing if a number is not correct. It is printing out No Solution followed by Abort Trap Error: 6. I am using a test case that should return TRUE. Row and Col are initially being passed in parameter as 0
What might be the issue? I'm thinking it could be how I am incrementing row and col. It reads in a single line file and translates to 2D grid
Here is test input: 4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......
#include <stdio.h>
#include <stdlib.h>
#define BLANK '.'
#define TRUE 1
#define FALSE 0
#define BLANK_SPACE '.'
int findBlankSpace(int grid2D[9][9]);
int valid(int grid2D[9][9], int rowIndex, int colIndex, int num);
void prettyPrint(int grid2D[9][9]);
int readLine(int grid2D[9][9]);
int findSolution(int grid2D[9][9],int row, int col);
int UsedInRow(int grid2D[9][9], int row, int num);
int UsedInCol(int grid2D[9][9], int col, int num);
int UsedInBox(int grid2D[9][9], int boxStartRow, int boxStartCol, int num);
int findSolution(int grid2D[9][9], int row, int col)
{
row = 0;
if (findBlankSpace(grid2D) == FALSE)
return TRUE;
if (row == 9) {
row = 0;
}
for (int num = 1; num <= 9; num++)
{
if (valid(grid2D, row, col, num))
{
grid2D[row][col] = num;
if (findSolution(grid2D, row, ++col))
{
return TRUE;
}
}
grid2D[row][col] = 0;
row++;
}
return FALSE;
}
int findBlankSpace(int grid2D[9][9])
{
int row;
int col;
for (row = 0; row < 9; row++)
for (col = 0; col < 9; col++)
if (grid2D[row][col] == 0)
return TRUE;
return FALSE;
}
int UsedInRow(int grid2D[9][9], int row, int num)
{
for (int col = 0; col < 9; col++)
if (grid2D[row][col] == num)
return TRUE;
return FALSE;
}
int UsedInCol(int grid2D[9][9], int col, int num)
{
for (int row = 0; row < 9; row++)
if (grid2D[row][col] == num)
return TRUE;
return FALSE;
}
int UsedInBox(int grid2D[9][9], int row1, int col1, int num)
{
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
if (grid2D[row+row1][col+col1] == num)
return TRUE;
return FALSE;
}
int valid(int grid2D[9][9], int row, int col, int num)
{
return !UsedInRow(grid2D, row, num) &&
!UsedInCol(grid2D, col, num) &&
!UsedInBox(grid2D, row - row % 3, col - col % 3, num);
}
int readLine(int grid2D[9][9])
{
int c;
int row = 0;
int col = 0;
while((c = getchar()) != EOF)
{
if(c == '.')
{
grid2D[row][col] = 0;
}
else
{
grid2D[row][col] = c - '0';
col++;
}
if(col%9 == 0)
{
row++;
col = 0;
}
}
return 0;
}
void prettyPrint(int grid2D[9][9])
{
int count = 0;
int row;
int col;
printf("solution:\n");
/* Use nested for-loops to iterate through 2-D array */
for(row = 1; row <= 9; row++)
{
for(col = 1; col<=9; col++)
{
/* After every 3rd character, print out "|", forming the board */
if((col%3==0)&&(col%9!=0))
{
printf("%d| ", grid2D[row - 1][col - 1]);
}
else
printf("%d ", grid2D[row - 1][col - 1]);
count++;
}
/* After every 3rd row, print out horizontal separations */
if((row%3==0)&&(row!=9))
{
/* Advance to the next line prior to printing separation to give space */
printf("\n");
printf("------+-------+------");
}
printf("\n");
}
}
int main()
{
int grid2D[9][9];
readLine(grid2D);
if(findSolution(grid2D, 0, 0)==TRUE)
{
prettyPrint(grid2D);
}
else
{
printf("No Solution Found!\n");
}
return 0;
}
in the recursive function: findSolution(), eventually the 'col' parameter will be 9 (or greater)! When that happens, the code will be accessing outside the bounds of the current row in the array. This results in undefined behavior and can lead to a seg fault event.

doesn't count extra numbers [magic square]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N_MAX 10
#define N_MIN 2
#define TEMPSIZE 1024
float RowSum(float **matrix, int sizearray,int row) {
float sum;
for (int j=0 ; j <= row; j++) {
sum = 0;
for (int i=0 ; i < sizearray; i++) {
sum = sum + matrix[j][i];
}
}
return sum;
}
float ColSum(float **matrix, int sizearray, int col) {
float sum;
for (int j = 0; j <= col; j++) {
sum = 0;
for (int i = 0; i < sizearray; i++) {
sum = sum + matrix[i][j];
}
}
return sum;
}
int RepNum(int arraysize, float **matrix) {
int i, j, counter = 0;
int temparray[N_MAX*N_MAX];
for (i = 0; i < N_MAX*N_MAX; i++) {
temparray[i] = 0;
}
for (i = 0; i < arraysize; i++) {
for (j = 0; j < arraysize; j++) {
temparray[(int)matrix[i][j]]++;
}
}
for (i = 1; i < arraysize*arraysize; i++) {
if (temparray[i] > 1)
counter++;
}
return counter;
}
void PrintArray(float **matrix, int arraysize) {
for (int i = 0; i<arraysize; i++)
{
for (int j = 0; j<arraysize; j++)
printf("%3d ", (int)matrix[i][j]);
printf("\n");
}
}
int CheckInt(float **matrix, int arraysize) {
int counter = 0;
for (int i = 0; i < arraysize; i++) {
for (int j = 0; j < arraysize; j++) {
if (((int)matrix[i][j]) != matrix[i][j])
counter++;
}
}
return counter;
}
void main() {
printf("Hello! this program will help you to find out if you have a magic square!\nPlease enter your matrix order and following it the numbers you'd like to check: \n");
float **matrix;
char input[TEMPSIZE];
int sizear = 0;
float correctsum = 0.0;
int counter = 0, row, column;
fgets(input, TEMPSIZE, stdin);
char* str = strstr(input, " ");
if (str == 0)
return;
str[0] = 0;
str++;
sizear = atof(input);
if (sizear > N_MAX || sizear < N_MIN)
{
printf("ERROR: The matrix size cannot be %d size. \n", sizear);
exit(0);
}
matrix = (float**)calloc(1, sizear * sizeof(float*));
for (column = 0; column < sizear; column++)
{
matrix[column] = (float*)calloc(1, sizear * sizeof(float));
}
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
char* temp = strstr(str, " ");
if (temp == 0) /*gets the last number*/
{
++counter;
matrix[row][column] = atof(str);
goto end;
}
if (atof(temp) <= sizear*sizear && atof(temp) > 0) { /*puts all numbers in matrix*/
temp[0] = 0;
matrix[row][column] = atof(str);
str = temp + 1;
++counter;
}
else {
printf("you cannot enter the number %.3f \n", atof(temp));
exit(0);
}
}
}
end:
if (counter > sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter < sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter == sizear*sizear) {
correctsum = (float)((sizear*(sizear*sizear + 1)) / 2);
float row = RowSum(matrix, sizear, 0);
float coul = ColSum(matrix, sizear, 0);
if (row == coul && row== correctsum && coul==correctsum && RepNum(sizear, matrix) ==0 && CheckInt(matrix,sizear)==0) {
printf("It's a magic matrix!\n");
PrintArray(matrix, sizear);
}
else {
printf("Not a magic square:\n");
if (row != coul && row != correctsum && coul != correctsum) {
printf("* Coloums and rows sum do not match.\n");
}
if (RepNum(sizear, matrix) != 0) {
printf("* There are repeating numbers.\n");
}
if (CheckInt(matrix, sizear) != 0) {
printf("* One of the numbers or more you've entered isn't integer.\n");
}
}
}
for (column = 0; column < sizear; column++)
{
free(matrix[column]);
}
free(matrix);
}
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
The exercise asked to check if the input is a magic square (sum rows=columns=diagonals), making sure there are no duplicates, only int numbers and that I don't enter more or less than sizearrayXsizearray numbers. The input from the user should look like 3 1 2 3 4 5 6 7 8 9 where the first number (here it is 3) is the array size and the rest are the numbers that would be checked as a magic square.
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
Sure, it's simple: the counter is incremented in the loops
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
…
}
}
- the inner statements are run through (at most) sizear × sizear times, so the counter, starting from 0, cannot reach a higher value.

Segmentation Fault: 11 C

I am making a simple command-line Candy Crush game. This is my code below. I'm writing it in xCode then running it in Terminal using pico. The gameboard prints out correctly, but it doesn't put Xs on the board. Instead the board is printed and then a segmentation fault occurs.
//
// Assignment 3
//
#include <stdio.h>`enter code here`
//function headers
void displayOriginal (int img[10][10], int col, int row);
void removeOriginal (int img[10][10], int col, int row);
int main(){
//declare variables and array
int col = 0;
int row = 0;
int img[10][10];
//call functions
displayOriginal (img, col,row);
removeOriginal (img, col, row);
displayOriginal (img,col,row);
return 0;
}
//function for displaying gameboard
void displayOriginal (int img[10][10], int col, int row){
for(row = 0; row < 10; row++){//to create rows 0-9
for(col = 0; col < 10; col++){//to create columns 0-9
scanf("%d", &img[row][col]);
}
}
printf(" 0 1 2 3 4 5 6 7 8 9\n");//adds labels to x axis
for(row = 0; row < 10; row++){
printf("%d", row);//add labels to y axis
for(col = 0; col < 10; col++){
if (img[row][col] == 1){ //red
printf("\x1b[41m ");
} else if (img[row][col] == 2){//green
printf("\x1b[42m ");
} else if (img[row][col] == 3){//purple
printf("\x1b[43m ");
} else if (img[row][col] == 4){//blue
printf("\x1b[44m ");
} else if (img[row][col] == 5){//magenta
printf("\x1b[45m ");
} else if (img[row][col] == 0){
printf("XX");
}
printf("\x1b[m"); //white
}
printf("\n");
}
}
//function to label where the X's go
void removeOriginal (int img[10][10], int col, int row){
//variables
int previous = -10;
int temp;
int tally = 1;
for(row = 0; row < 10; row++){
for(col = 0; col < 10; col++){
if (previous == img[row][col]){//if previous block =current then add 1
tally++;
} else {
tally = 1;//return to 1 if previous does not equal current
}
if (tally >= 3){
previous = img[row][col];
for (temp = (tally-1); temp >= 0; temp--){
img [row-temp][col] = 0;
}
} else {
previous = img [row][col];
}
printf("Row %d Col %d Tally %d", row, col, tally);
}
}
}
Are you certain that row >= temp in this section? If it isn't, img[-1][col] will result in a segmentation fault.
if (tally >= 3)
{
previous = img[row][col];
for (temp = (tally-1); temp >= 0; temp--)
{
img [row-temp][col] = 0;
}
}

Resources