cstrcat

why the outcome is helloworld123456?? instead of helloworld 1234567


#include<stdio.h>
#include <string.h>

char* mystrcat(char* s1, const char* s2);

int main() {
    char s1[] = "helloworld";
    char s2[] = "1234567";

    printf("%s\n", mystrcat(s1,s2));
    return 0;
}

char* mystrcat(char* s1,const char* s2) {
    int idx=0;
    char *p=s1;

    while(s2[idx]) {
        s1[strlen(s1)] = s2[idx];
        idx++;
    }

    s1[strlen(s1)] = '\0';
    return p;
}

Solution

  • Arrays have a fixed size. You can't extend an array. And when you create your arrays:

    char s1[]="helloworld";
    char s2[]="1234567";
    

    then they will have the size they are initialized with: s1 will be 11 elements long, and s2 will be 8 characters long.

    So the first problem is that you attempt to add elements to s1, but it doesn't fit any more elements. You need to make sure it can hold space for at least 18 characters:

    char s1[30]="helloworld";  // 30 should be well enough for this simple test
    

    Then we come to the second problem, which happens when you do:

    s1[strlen(s1)] = s2[idx];
    

    This works only for the first appending to s1. That first assignment will overwrite the null-terminator, and after this the string in s1 is no longer a null-terminated string and you can't use strlen to get its length.

    You need to keep track of the s1 position using a variable, similarly to what you do for s2.


    However, once these issues are fixed, the output will still not be helloworld 1234567, because you don't add any space between the two strings.