Home > OS >  How to prevent matrix from accessing unnallowed values
How to prevent matrix from accessing unnallowed values

Time:01-10

Hello I created a random 6x6 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?

CodePudding user response:

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.

  •  Tags:  
  • Related