Why one variable can not be read after swaping two variables

Asked 2 months ago
Viewed 9 times

In the output, there is only water is printed, but no soda is printed. But in my opinion, soda has less size, it should be easily saved in x because x has a bigger size. If I set y who has more chars than x, then it doesn't have such a problem.

#include <stdio.h>
#include <string.h>

int main()
  char x[] = "water";
  char y[] = "soda";
  char temp[10];

  strcpy(temp, x);
  strcpy(x, y);
  strcpy(y, temp);

  printf("%s", x);
  printf("%s", y);
  printf("%d", sizeof(x));
  printf("%d", sizeof(y));
  return 0;

asked 2 months ago

Correct Answer

The provided code invokes undefined behavior because the size of the array y is less than the size of the array x. So you may not copy the array x into the array y.

answered 2 months ago