-4

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);
}
Steve Bob
  • 5
  • 5

1 Answers1

1

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;
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • I know there are other ways to create this function , and it did make sense to me that the content is being over written , but i sew this example in the book Ritchie/Kernighan and i want to understand why they presented it if it doesn't work ? – Steve Bob Aug 02 '22 at 04:54