Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong print in C program

Tags:

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

First printf prints 1 while the other printf prints 9 . And I haven't changed i in the meantime as you can see. Why does it print 9?

like image 322
domdrag Avatar asked Dec 24 '22 20:12

domdrag


1 Answers

You refer to x[j+1] when j is 5. That's outside the bounds of the array.

The behaviour of your code is therefore undefined. (Interestingly, the behaviour of your code is consistent with x[6] being equivalent to j, and x[7] being i and a particular sequencing in the assignment, but don't rely on any of that.)

like image 135
Bathsheba Avatar answered Jan 02 '23 05:01

Bathsheba