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

in C language, how to verfify if the position in M[][] is valid?

Guys, do you know when i try to access the position like this:

M[-2][-1], DONT WORK,

But, if we try to access like:

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

int k = -2;

M[k][k+1], WORKS?

i’m doing a homework and i need to verify if the M position is valid on base in some randoms I and J.

    #include <stdio.h>
int main(){
  int matriz[5][5];
  int i, j;
  int cont = 0;
  for(i=0;i<5;i++){
    for(j=0;j<5;j++){
      matriz[i][j] = cont+=1;
    }
  }
  for(i=0;i<5;i++){
    for(j=0;j<5;j++){
      printf("%d ",matriz[i][j]);
    }
    printf("\n");
  }
  
  int k = -2;
  //matriz[-2][-1] = 99; << dont work
  matriz[k][k+1] = 99; // << this works
  printf("\n%d",matriz[k][k+1]); << this works
  printf("\n\n");
  for(i=0;i<5;i++){
    for(j=0;j<5;j++){
      printf("%d ",matriz[i][j]); //<< and this dont change anything on matriz
    }
    printf("\n");
  }
  
}

>Solution :

It "works" as in the compiler might allow it, but do not do this because you are changing memory that does not belong to the array and will very likely cause a crash or worse.

You can check in your function by passing in i and j, and also the number of rows and columns.

if (i >= 0 && j >= 0 && i < MAX_ROWS && j < MAX_COLS) {
    matriz[i][j] ... do something
} else {
    invalid
}
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