Hello I created a random 6×6 matrix int S[6][6] and the issue is that when I try to access the value of an unexisting square like S[6][-1] square it should return 0 but instead it returns the S[5][5] square. if I try dynamic allocation,I get 0x0005 seg fault.
2 1 2 1 2 1
2 1 1 2 1 1
2 2 1 1 2 1
1 2 1 1 1 2
1 2 2 2 1 1
1 1 1 2 2 2 //S[0][6] = S[1][0]
is there a way to fix this?
>Solution :
You should probably implement a function for doing that. It could look like this:
int matrix_get_value(int row, int column) {
if(row < 0 || row >= 6 || column < 0 || column >= 6)
return 0;
return matrix[row][column];
}
It could also be done in a more dynamic way by passing the matrix as a function parameter
int matrix_get_value(int **matrix, int size_rows, int size_columns, int row, int column) {
if(row < 0 || row >= size_rows || column < 0 || column >= size_columns)
return 0;
return matrix[row][column];
}
In this solution the matrix is passed to the function as a double pointer (pointer to pointer), but this can be done in other ways too.