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

Time:01-05

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:

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");
  }
  
}

CodePudding user response:

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
}
  •  Tags:  
  • Related