Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent matrix from accessing unnallowed values

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading