2

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Elias
  • 179
  • 8

2 Answers2

2

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));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • But actually, i can copy x into y, but not y into x. do u know the reason – Elias Sep 25 '22 at 21:16
  • 1
    @Elias As I wrote copying x in the array y invokes undefined behavior because the memory beyond the array y will be overwritten. The array y contains only 5 elements but you are copying 6 elements from the array x. – Vlad from Moscow Sep 25 '22 at 21:19
1

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;
Z4-tier
  • 7,287
  • 3
  • 26
  • 42
  • do u know the reason – Elias Sep 25 '22 at 20:52
  • `printf("%d", sizeof(x))` leads to undefined behavior. Conversion specifiers are required to match their arguments, and the appropriate conversion specifier for `size_t` (the type yielded by the `sizeof` operator) is `%zu` Also, `char x[6] = ...` could simply be `char x[] = ...`, but this hardcoding of array dimensions to suit imagined operations is probably not the right solution except for limited toy examples. – ad absurdum Sep 25 '22 at 21:08