Appending strings in C

前端 未结 6 1841
无人共我
无人共我 2020-12-12 02:21

How do I combine multiple strings. For example,

char item[32];
scanf(\"%s\", item);
printf(\"Shopping list: %s\\n\", item); //I want to combine this string          


        
6条回答
  •  时光取名叫无心
    2020-12-12 03:00

    Processing raw strings in C is always ugly. You have to do two steps to concatenate strings:

    1. Allocate memory for the new string.

    2. Copy the source strings into your new buffer.

    As a lesson, please note that there are already three different answers to this question with three different buffer overrun errors.

    Here is a function which concatenates two strings and returns a new string:

    char *astrcat(const char *x, const char *y)
    {
        size_t nx = strlen(x), ny = strlen(y);
        char *z = malloc(nx + ny + 1);
        if (!z)
            return NULL;
        memcpy(z, x, nx);
        memcpy(z + nx, y, ny + 1);
        return z;
    }
    

    You can expand this to work with three strings, or you can just call it twice. Sane folk tend to use a library or make extensive use of fixed-size buffers.

    Alternative: With fixed-size buffers and snprintf, you get safety and ease of use but you're stuck with fixed size buffers.

    const char *x = ..., *y = ...;
    char buf[100];
    snprintf(buf, sizeof(buf), "%s%s", x, y);
    

    If you don't have snprintf, then you're probably using MSVC, which has _snprintf which is almost the same but doesn't always nul-terminate the output.

    Don't use strcat or strcpy: There are very few circumstances in which strcat is acceptable:

    char buf[100];
    strcpy(buf, x); // buffer overflow
    strcat(buf, y); // buffer overflow
    

    Don't use sprintf: It also overflows:

    char buf[100];
    sprintf(buf, "%s%s", x, y); // buffer overflow
    

提交回复
热议问题