简体   繁体   中英

Why one variable can not be read after swaping two variables

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM