Search code examples
cc-stringsstrcpystrcat

Program Prints the string in the wrong way. strcpy


After I put the input for name and surname (example: name:Mario surname:Rossi) As an output instead of getting Mario Rossi I get ossi Rossi but I can't understand why.

int main() {
    char space[] = " ";
    char name[40], surname[40], space_name[40], space_surname[40];
    printf("what's your name");
    scanf("%[^\n]", &name);

    printf("Whats your surname");
    scanf(" %[^\n]", &surname);

    strcpy(space_surname, strcat(space, surname));
    strcat(name, space_surname);
    printf("%s", name);
}

Solution

  • strcat(dest, src) will concatenate src onto dest. Your buffer space (length 1 not including null-terminator) isn't large enough to hold both. Also, your space_surname will overflow, as you're storing a size 1 string (space) and a size 40 string (surname) into a size 40 buffer. Increase it to at least size 41. Having a space string is also unnecessary, as space is character and can be set directly.

    space_surname[0] = ' ';
    space_surname[1] = '\0';  // So you know where to concat to
    strcat(space_surname, surname);
    

    Note you run into the same issue with name. You're trying to store name (length 40), space (length 1), and surname(length 40) all into name. You need to create a new full_name variable of size 81 or greater and store into that.