Edit3: Added Example.
Edit2: So, because I am new to coding in general and because of the current comments,I need to ask, would it be better if I posted the entire code as a comment? (around 90 lines)
So, I have been playing around with dynamic memory allocation and I have a 2D board, witch fills with '.'. Then I import the board in a function, witch checks for available cells (cell with '.'==available). It compiles ok, but when I run it I get
segmentation fault
Here's the code for the board malloc
**board = (char**) malloc(x_input*sizeof(char*));
for(i = 0; i <x_input; i++){
board[i] = (char*) malloc(y_input*sizeof(char));
}
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
Here's the Function
int checker(int x_axis, int y_axis, char **board){
if (board[x_axis][y_axis] == '.'){
return 1;
} else {
return 2;
}
}
And here's the only time(so far) that I call the function
Edit: x_replacement
and y_replacement
are assigned random values through a rand function
do{
board[x_replacement][y_replacement] = '$';
} while(checker(x_replacement, y_replacement, board) == 2);
EX:
const int MAX_X = 40;
const int MAX_Y = 40;
const int MIN_X = 20;
const int MIN_Y = 20;
int x_input, y_input;
int main(void){
char **board;
int i, j, k, obstacles, enemies, choice;
do{
printf("Enter board size. (Must be between (%d, %d) and (%d, %d))\n:", MIN_X, MIN_Y, MAX_X, MAX_Y);
scanf("%d%d", &x_input, &y_input);
}while ((x_input <= MIN_X && x_input >= MAX_X) && (y_input <= MIN_Y && y_input >= MAX_Y));
*board = malloc(sizeof(char[x_input][y_input]));
assert(*board != NULL);
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
return 0;
}