It should be
*str1 = '\0';
since it has already been incremented.
In a simplified version
while (c-- > 0) *str1++ = *str2++;
you can easily see that when c
is 1
, *str1
gets *str2
value, and is incremented, thus str1
is pointing after the value that has just been set. Thus using directly str1
pointer to set the final 0
to indicate the end of the string can be written as
while (c-- > 0) *str1++ = *str2++;
*str1 = 0;
(actually '\0'
represents a char value of zero, thus writing directly 0
works as well)
Also, (thanks to @Guillaume_Morin for mentioning that) the function should better return a pointer to the beginning of the result string (str1), and you need to keep a copy of the initial str1 for that, since it is incremented later on:
char * strncpy_own(char * str1, char * str2, int c) {
char *str1copy = str1;
while (c-- > 0) *str1++ = *str2++;
*str1 = 0;
return str1copy;
}