垃圾值;奇怪的字符串 strlen 值

Garbage values; strange string strlen value

我正在尝试编写一个函数,以指定值将一个字符串插入另一个字符串。它在新字符串的末尾返回了一些垃圾值,大概是因为由于某种原因,新字符串的 strlen 比它应该的大; strlen(combo) 应该等于 s1 + s2 但事实并非如此。我不确定为什么它返回 13 而不是 9 作为长度。这是我的代码:

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

void insertString(char *string1, char *string2, int position) {
    int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);
    char combo[s1 + s2];

    for (i = 0; i < s1 + s2; i++) {
        combo[i] = i;
    }

    for (i = 0; i < s1 + s2; i++) {
        if (i < position) {
            combo[i] = string1[i];
            j++;
        }
        else if (i >= position && i < position + s2) {
            combo[i] = string2[k];
            k++;
        }
        else if (i >= position + s2) {
            combo[i] = string1[j];
            j++;
        }
    }
    for (i = 0; i < strlen(combo); i++){
        printf("%c", combo[i]);
    }

    printf ("\n comboLength = %lu\n", strlen(combo));
    printf ("s1 = %d\n", s1);
    printf ("s2 = %d\n", s2);
}


int main (void) {
    insertString("I pie", "like", 2);

    return 0;
}

编辑:添加了空字符。仍然返回新字符串右侧几个空格的单个垃圾值,并且仍然没有返回 9 作为正确的字符串长度。

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

void insertString(char *string1, char *string2, int position) {
    int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);
    char combo[s1 + s2];

    for (i = 0; i <= s1 + s2; i++) {
        combo[i] = i;
    }

    for (i = 0; i < s1 + s2; i++) {
        if (i == s1 + s2) {
            combo[i] = '[=11=]';
        }
        else if (i < position) {
            combo[i] = string1[i];
            j++;
        }
        else if (i >= position && i < position + s2) {
            combo[i] = string2[k];
            k++;
        }
        else if (i >= position + s2) {
            combo[i] = string1[j];
            j++;
        }
    }
    for (i = 0; i < strlen(combo); i++){
        printf("%c", combo[i]);
    }

    printf ("\n comboLength = %lu\n", strlen(combo));
    printf ("s1 = %d\n", s1);
    printf ("s2 = %d\n", s2);
}


int main (void) {
    insertString("I pie", "like", 2);

    return 0;
}

您的组合字符串中缺少终止符 \0。 strlen() returns 不包括终止空字节的长度。