In the Ritchie/Kernighan book, they show a few ways how to create a self made strcpy function, one of them is with using array subscribed instead of char pointers, but when I try this method and run the code it only gives me the second word in this case "world" and not the word "hello" any clue?
#include <stdio.h>
void xstrcpy(char *a, char *b)
{
int i = 0;
while((a[i] = b[i]) != '\0')
{
i++;
}
}
int main()
{
char name[20] = "hello";
char names[20] = "world";
xstrcpy(names, name);
printf("%s\n", names);
}
Your function overwrites a
with the content of b
. You could call as like this:
xstrcpy(names + strlen(names), name);
Or you could implement concatenation. Require caller to pass in a sufficiently large string array ( dest
). Then find the end ( end
) of the string and copy src
to dest
. Using the pointers passed in, but you could also use separate indices into dest
and src
:
#include <stdio.h>
#include <string.h>
// require caller to pass in a dest array large enough for a copy of src
char *xstrcat(char *dest, const char *src) {
char *end = strchr(dest, '\0');
while(*end++ = *src++);
return dest;
}
int main() {
char dest[sizeof("hello") + sizeof("world") - 1] = "hello";
char src[] = "world";
xstrcat(dest, src);
printf("%s\n", dest);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.