0

The task is to reproduce the behavior of the function strcpy in C. I found this code:

char    *ft_strcpy(char *s1, char *s2)
{
    int i;

    i = 0;
    while (s2[i])
    {
        s1[i] = s2[i];
        i++;
    }
    s1[i] = s2[i];
    return (s1);
}

I don't understand the while condition. Why can I just put "s2[1]" as condition? What does the condtion say in this context?

Barmar
  • 741,623
  • 53
  • 500
  • 612
mr_bean
  • 5
  • 3
  • 1
    Strings in C end with a NUL character which evaluates to false when used as a boolean. – kaylum Jan 05 '21 at 20:00
  • While `s2[i]` is not zero. – bipll Jan 05 '21 at 20:00
  • 5
    `while (x)` is the same as `while (x != 0)`. – dxiv Jan 05 '21 at 20:01
  • 3
    I see a conflict between the idea of a homework assignment like "reproduce strcpy" and an approach to solve that by trying to "find" it. The learning goal surely is intended to be achieved by writing the function, based on what previous lessons taught. So my question is, what is your understanding of what the core loop of that function should cover and how would you write the loop condition to achieve that? If you have an opinion of that, then probably you might find that the condition you do not understand in the shown code does the same thing just "cooler" (which is not necessarily better). – Yunnosch Jan 05 '21 at 20:17
  • @IrAM apart from that it copies s1 to s2, the opposite of the OP's task? – Gerard H. Pille Jan 05 '21 at 20:25
  • You can even simplify it to `char *result = s1; while (*s1++ = *s2++) {}; return result;` – selbie Jan 05 '21 at 20:28

1 Answers1

1

It checks the value of s2[i]. The string terminator '\0' has value 0. So it will loop until the end of the string.

The line s1[i] = s2[i]; is added to put the '\0' at the end.

By definition, a C-style string is a sequence of chars ended in '\0'. If you forget to put it at the end you probably will get into trouble.

vmp
  • 2,370
  • 1
  • 13
  • 17