c - 在我的字符串中获取垃圾

标签 c string pointers malloc garbage

我正在编写一个程序,它接受两个字符串并将一个字符串输入另一个字符串,以便:

  • 字符串 1:abc

  • 字符串 2:123

  • 输出:a123b123c123

现在由于某种原因,我的输出字符串在中间出现垃圾:a123=b123=c123。我不知道为什么,希望得到一些帮助!

代码如下:

#define _CRT_SECURE_NO_WARNINGS
#define N 80
#define ONE 1
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

void InputStr(char str[]);
char* CreateString(char str1[], char str2[]);
int main()
{
    char strA[N], strB[N], *strF;

    InputStr(strA);
    InputStr(strB);
    strF = CreateString(strA, strB);
    puts(strF);

}

void InputStr(char str[])
{

    printf("Please enter the string\n");
    scanf("%s", str);


}
char* CreateString(char str1[], char str2[])
{

    char* newstr;
    int len1, len2, size, i, j, b;
    len1 = strlen(str1);
    len2 = strlen(str2);
    size = len1*len2;
    newstr = (char*)malloc(size*sizeof(char) + 1);
    for (i = 0, b = 0; i<len1; i++, b++)
    {
        newstr[b] = str1[i];
        b++;
        for (j = 0; j<len2; j++, b++)
            newstr[b] = str2[j];


    }
    newstr[b + ONE] = 0;
    printf("test\n");
    return newstr;


}

最佳答案

你的问题

您将 b 变量递增 2 次:

for (i = 0, b = 0; i < len1; i++, b++) // First increment
{
    newstr[b] = str1[i];
    b++; // Second increment
    for (j = 0; j < len2; j++, b++)
        newstr[b] = str2[j];
}

解决方案

只需删除第一个 b 增量,您的代码就可以工作:

for (i = 0, b = 0; i < len1; i++) // No more b increment
{
    newstr[b] = str1[i];
    ++b; // You only need this increment
    for (j = 0; j < len2; j++, b++)
        newstr[b] = str2[j];
}

关于c - 在我的字符串中获取垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48007629/

相关文章:

使用 cairo 绘制点时剪裁

c - 逐个获取 vsnprintf() 输出

PHP mb_substr() 无法正常工作?

c - void* 与 char* 指针算法

c - 为什么会出现这个段错误?

c - 从 C 中的字符串中删除最常见的单词

python - list(a) 和 [a] 有什么区别?

c - 跟踪C中链表的头节点

c - 段错误但找不到错误

我们可以将权限从用户更改为 root 吗?