Invalid printing in program C

#include <stdio.h>
int main() {
  int x[] = {2, 3, 1, 5, 6, 9};
  int j, i, s;
  for (i=0; i<6; i++){
    if (x[i] % 2 == 1){
      break;
    }
  }

  printf("%d", i);
  for (j=5; j>1; j--){
    x[j+1] = x[j];
  }
  printf("%d", i);

  return 0;
} 

The first printfprints 1, and the other printfprints 9. And I have not changed iin the meantime, as you can see. Why is he typing 9?

+4
source share
1 answer

You can refer to x[j+1]if j- 5. This is outside the bounds of the array.

Thus, the behavior of your code is undefined. (It is interesting that the behavior of your code is consistent with the x[6]equivalent j, and x[7]- iand a certain order in the appointment, but does not rely on any of them.)

+10
source

Source: https://habr.com/ru/post/1669170/


All Articles