C: String Concatentation: Null Terminated Strings

删除回忆录丶 提交于 2020-01-05 06:53:21

问题


The following code only concatenates the first string and ignores the second.. from what I gather, it has something to do with Null terminated strings. As I am new to C, this is a new concept to me. Could someone help make the code below work? That would really help me a lot in understanding this.

void concatTest();

int main()
{
    concatTest();

    system("PAUSE");
    return 0;
}

void concatTest()
{
    char string1[20], string2[20], string3[40];
    char *ptr1, *ptr2, *ptr3;
    ptr1 = &string1[0];
    ptr2 = &string2[0];
    ptr3 = &string3[0];
    int i;

    printf("You need to enter 2 strings.. each of which is no more than 20 chars in length: \n");

    printf("Enter string #1: \n");
    scanf("%s", string1);

    printf("Enter string #2: \n");
    scanf("%s", string2);

    int len1 = strlen(string1);
    int len2 = strlen(string2);

    for (i = 0; i < len1; i++)
    {
        ptr3[i] = ptr1[i];
    }
    for (i = len1; i < len1 + len2; i++)
    {
        ptr3[i] = ptr2[i];
    }

    printf("%s\n", string3);
}

回答1:


You are indexing ptr2[i] using i which ranges from len1 to len1 + len2. This value will probably be out of bounds of the string2 array (unless the first string you type happens to be empty).

I might write your second loop as follows:

for (i = 0; i < len2; i++) {
    ptr3[len1 + i] = ptr2[i];
}



回答2:


My answer will have no code, but hopefully a useful explanation.

Each string in C is terminated with \0.

If you want to concatenate two strings you need to be sure you overwrite the last character of the first string (the \0) with the first character of the 2nd string. Otherwise, no matter how long the "concatenated" string is, as soon as a \0 is encountered by a string function, it will assume the end of the string has reached.

And of course you need to be sure you have enough allocated space for the joint string.




回答3:


You have to start at the first character of ptr2.

ptr3[i] = ptr2[i-len1];

from what I gather, it has something to do with Null terminated strings.

Yes it does. Strings start at offset 0. You were starting at some random point based on the length of the fist string.



来源:https://stackoverflow.com/questions/11496624/c-string-concatentation-null-terminated-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!