简体   繁体   English

C:字符串合并:空终止的字符串

[英]C: String Concatentation: Null Terminated Strings

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. 以下代码仅连接第一个字符串,而忽略第二个..从我收集的内容来看,它与Null终止的字符串有关。 As I am new to C, this is a new concept to me. 由于我是C语言的新手,所以对我来说这是一个新概念。 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);
}

My answer will have no code, but hopefully a useful explanation. 我的答案没有代码,但希望能提供有用的解释。

Each string in C is terminated with \\0 . C中的每个字符串都以\\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. 如果你想连接两个字符串,你需要确保你覆盖第一个字符串( 的最后一个字符 \\0 )与第二个字符串的第一个字符。 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. 否则,无论“级联”字符串有多长,字符串函数一旦遇到\\0 ,都将假定已到达字符串的末尾。

And of course you need to be sure you have enough allocated space for the joint string. 当然,您需要确保为连接字符串分配了足够的空间。

You are indexing ptr2[i] using i which ranges from len1 to len1 + len2 . 您正在使用范围从len1len1 + len2 i索引ptr2[i] This value will probably be out of bounds of the string2 array (unless the first string you type happens to be empty). 该值可能超出string2数组的范围(除非您键入的第一个字符串碰巧为空)。

I might write your second loop as follows: 我可能会如下所述编写第二个循环:

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

You have to start at the first character of ptr2. 您必须从ptr2的第一个字符开始。

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

from what I gather, it has something to do with Null terminated strings. 从我收集的数据来看,它与Null终止的字符串有关。

Yes it does. 是的,它确实。 Strings start at offset 0. You were starting at some random point based on the length of the fist string. 字符串从偏移量0开始。您是根据拳头字符串的长度从某个随机点开始的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM