Home > front end >  Why one variable can not be read after swaping two variables
Why one variable can not be read after swaping two variables

Time:09-26

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

CodePudding user response:

The provided code invokes undefined behavior because the size of the array y (equal to 5) is less than the size of the array x (equal to 6). So you may not copy the array x into the array y using the function strcpy.

You could declare the array y for example the following way

char x[] = "water";
char y[sizeof( x )] = "soda";

Pay attention to that the array sizes are not changed. They have compile-time values because the declared arrays are not variable length arrays. It seems you wanted to compare lengths of the stored strings using the function strlen as for example

printf("%zu\n", strlen(x));
printf("%zu\n", strlen(y));

Also the both the operator sizeof and the function strlen yield values of the type size_t. So you have to use the conversion specifier %zu instead of %d in calls of printf as for example

printf("%zu\n", sizeof(x));
printf("%zu\n", sizeof(y));

CodePudding user response:

The other answer is correct, but I'll add that the way to fix is to specify the size of the arrays:

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

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

  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;
  • Related