This is my code. I am trying to simulate strcpy(). This code works, but I have a couple questions.
#include <stdio.h>
#include <stdlib.h>
char *strcpy(char *d, const char *s);
int main()
{
char strOne[] = "Welcome to the world of programming!";
char strTwo[] = "Hello world!";
printf("String One: %s\n", strOne);
printf("String Two before strcpy(): %s\n", strTwo);
strcpy(strTwo, strOne);
printf("String Two after strcpy(): %s\n", strTwo);
return 0;
}
char *strcpy(char *d, const char *s)
{
while (*s)
{
*d = *s;
d++;
s++;
}
*d = 0;
return 0;
}
When *s gets incremented to the position where '\0' is stored in the array, is that when the while condition becomes false because of '\0'? Does while read '\0' or just '0'?
'while' condition will be true if it reads '1'. All previous values of *s should be read as single characters in while condition, but the loop executes anyways. Why does this happen? Do all the single characters from the array *s is pointing equate to the value '1'?
What does
*d = 0;
exactly do? The way I understand it, the copying process is completed when the while loop is exited. So why does removing*d = 0
lead to an incorrect output being displayed?
Output without *d = 0
:
String Two before strcpy(): Hello world!
String Two after strcpy(): Welcome to the world of programming! programming!
Output with *d = 0
:
String Two before strcpy(): Hello world!
String Two after strcpy(): Welcome to the world of programming!