C:字符串连接:空终止字符串 [英] C: String Concatentation: Null Terminated Strings

查看:153
本文介绍了C:字符串连接:空终止字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code只地连接了第一个字符串,而忽略第二..从我收集,它是与空结束的字符串。由于我是新来C,这是一个新的概念给我。可能有人帮助下面的工作code?这将真正帮助我很多理解这一点。

 无效concatTest();诠释的main()
{
    concatTest();    系统(暂停);
    返回0;
}无效concatTest()
{
    炭字符串1 [20],字符串2 [20],STRING3 [40];
    的char * ptr1的,* PTR2,* ptr3;
    ptr1的=安培;字符串1 [0];
    PTR2 =安培;字符串2 [0];
    ptr3 =安培; STRING3 [0];
    INT I;    的printf(您需要输入两个字符串..每一个的长度不超过20个字符:\\ n);    的printf(请输入字符串#1:\\ n);
    scanf函数(%S,字符串1);    的printf(请输入字符串#2:\\ n);
    scanf函数(%S,字符串2);    INT LEN1 = strlen的(字符串1);
    INT LEN2 = strlen的(字符串2);    对于(i = 0; I< LEN1;我++)
    {
        ptr3 [I] = ptr1的[I]
    }
    对于(i = LEN1; I< LEN1 + LEN2;我++)
    {
        ptr3 [I] = PTR2 [I]
    }    的printf(%S \\ n,STRING3);
}


解决方案

您正在使用索引 PTR2 [I] I 的取值范围为 LEN1 LEN1 + LEN2 。这个值可能会出字符串2 数组边界的(除非您键入的第一个字符串正好是空的)。

如下我可以写你的第二个循环:

 为(i = 0; I< LEN2;我++){
    ptr3 [LEN1 +我= PTR2 [I]
}

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);
}

解决方案

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];
}

这篇关于C:字符串连接:空终止字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆