I'm trying to pass a recursive function that populates my 2D array of structs. My memory allocation is working fine, but when I try to do a recursion, I get the error: Segmentation fault (core dumped). Any idea why this must be happening? I think I wrote my code so that no index out of bound occurs. I still don't know why this is happening. Any help is going to be appreciated. Thanks!
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct {
char val;
bool filled;
} elements;
void assign(elements ** elements, int row, int column, int x, int y, int limit);
int main(int argc, char** argv)
{
int row = 0;
int column = 0;
int x = 0;
int y = 0;
int limit = 0;
sscanf(argv[1], "%d", &row);
sscanf(argv[2], "%d", &column);
sscanf(argv[3], "%d", &x);
sscanf(argv[4], "%d", &y);
sscanf(argv[5], "%d", &limit);
elements **foo;
foo = (elements **)malloc(sizeof(elements *) * row);
for (int i = 0; i < column; i++)
foo[i] = (elements *)malloc( sizeof(elements) * row);
foo[y][x].val = 'C';
// printf("%c\n", foo[y][x].val);
assign(foo, row, column, x, y, limit);
for(int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
// foo[i][j].val = '.';
printf("%d\t ", foo[i][j].filled);
}
printf("\n");
}
}
void assign(elements ** elements, int row, int column, int x, int y, int limit)
{
int tempX = x;
int tempY = y;
if(elements[y][x].filled != 0 )
{
//printf("reached.");
return;
}
else if(limit < 0)
{
//printf("reached.");
return;
}
else
{
if(elements[y][x].val != 'C')
elements[y][x].val = limit + '0';
elements[y][x].filled = true;
tempX = x - 1;
tempY = y;
if (!( x < 0 || y < 0 || x > column - 1 || y > row -1 ))
assign(elements, row, column, tempX, tempY, limit - 1); // go up
tempX = x;
tempY = y + 1;
if (!( x < 0 || y < 0 || x > column - 1 || y > row -1 ))
assign(elements, row, column, tempX, tempY, limit - 1); // go right
tempX = x + 1;
tempY = y;
if (!( x < 0 || y < 0 || x > column - 1 || y > row -1 ))
assign(elements, row, column, tempX, tempY, limit - 1); // go down
tempX = x;
tempY = y - 1;
if (!( x < 0 || y < 0 || x > column - 1 || y > row -1 ))
assign(elements, row, column, tempX, tempY, limit - 1); // go left
}
}