Skip to main content

ft_strcpy — Copy a String

Allowed functions: none

Reproduce the behavior of the function strcpy (man strcpy).

char    *ft_strcpy(char *s1, char *s2);

Solution

Download ft_strcpy.c
char *ft_strcpy(char *s1, char *s2) {

int i = 0;
while (s2[i]) {

s1[i] = s2[i];
i++;
}
s1[i] = '\0';

return s1;
}

How It Works

Goal: Copy a source string into a destination buffer, including the null terminator.

Approach: Use an index variable to copy characters one by one from s2 to s1, then manually null-terminate.

Step by step:

  1. Initialize an index i to 0.
  2. Loop while s2[i] is not the null terminator, copying each character from s2[i] to s1[i].
  3. After the loop, set s1[i] = '\0' to null-terminate the destination string.
  4. Return the pointer to s1.

Key concept: Array indexing and null termination — understanding that C strings must end with '\0' and that copying a string means copying every character plus the terminator.