I'm trying to implement the strcpy
function by myself. The original strcpy
is part of the the string.h
library.
char *strcpy(char *dest, const char *src)
{
assert(dest != NULL && src != NULL);
char *temp = dest;
while (*src)
{
*dest = *src;
src++;
dest++;
}
return temp;
}
void strcpyTest()
{
char source[20] = "aaaaaa";
char dest1[20] = "bbbbbbbbb";
char desta[10]="abcd";
puts(dest1); // bbbbbbbbb
strcpy(dest1, source);
puts(dest1); // aaaaaa
strcpy(desta, source);
puts(desta); // aaaaaa
strcpy(desta, dest1);
puts(desta); // aaaaaa
strcpy(dest1, desta);
puts(dest1); // aaaaaa
strcpy(source, desta);
puts(source); // aaaaaa
}
As you can see, even the first call for the function with a longer dest
than the src
gives the right result although, by logic, it should give
aaaaaabb
and not aaaaaa
:
char source[20] = "aaaaaa";
char dest1[20] = "bbbbbbbbb";
strcpy(dest1, source);
puts(dest1);
/** aaaaaa **/
Why does my function work? I would guess that i'll have to manually add the /0
char in the end of *dest*
after the while
(*src)` will exit.
I mean the whole point of this while (*src)
is to exit when it reaches the end of *src*
which is the last char in the string which is /0
.
Therefore, I would guess i'll have to add this character to *dest*
by myself but the code somehow works and copies the string without the manual addition of /0
.
So my question is why and how it still works?
When I create a new array, lets say
int *arr
orchar *arr
, of 10, i.echar arr[10]
orint arr[10]
and I initialize only the 2 first indexes, what happens to the values that inside the rest of the indexes? Does they will be filled with zeros or garbage value or what?
Maybe my code works because it filled with zeros and that's why the while
loop stops?