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.cchar *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:
- Initialize an index
ito 0. - Loop while
s2[i]is not the null terminator, copying each character froms2[i]tos1[i]. - After the loop, set
s1[i] = '\0'to null-terminate the destination string. - 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.