简体   繁体   English

为什么变量i在循环中不增加?

[英]Why is variable i not incremented in the loop?

What's the problem here? 这是什么问题 I was trying to concatenate two strings. 我试图连接两个字符串。

Here's the full code. 这是完整的代码。 Only first string is printed. 仅打印第一个字符串。

#include<stdio.h>
main()
{
    char s[100],s2[100];
    printf("Enter a String\n");
    scanf("%s",&s);
    printf("Enter second String\n");
    scanf("%s",&s2);
    int i=strlen(s);
    //printf("%d",i);
    int j;


    for(j=0;s2[j]!='\0';++j)
    {
        i+=1;
        s[i]=s2[j];
    }

    printf("%s",s);
}

As already commented, you jump over the terminator of s, change to 如前所述,您跳过的终止符,更改为

for(j=0;s2[j]!='\0';++j)
{
    s[i]=s2[j];
    i+=1;
}
s1[i]='\0'; // terminated after concatenation

and you should be there. 你应该在那里 Keep in mind that if you dont check the length of the resulting string you may overflow the s[100] array. 请记住,如果不检查结果字符串的长度,则可能会使s [100]数组溢出。

If you want write this more secure and dont overflow the s variable use this: 如果您想更安全地编写此代码,并且不要使s变量溢出,请使用以下代码:

size_t size = strlen(s) + strlen(s2);
char* result = (char*) malloc(sizeof(char) * size + 1);
sprintf(result, "%s%s", size);

This is simple and safe. 这是简单且安全的。 And do it in function to automatic free s and s2 . 并在功能上做到自动释放ss2

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

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