在我的字符串中获取垃圾

问题描述 投票:1回答:3

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

  • 字符串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;


}
c string pointers malloc garbage
3个回答
3
投票

你的问题

你正在增加你的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];
}

2
投票

你每次都在增加b。(这也是两次)只要你需要它就可以。否则字符串中有孔。

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

那么一个小小的改变就是

newstr[b] = 0;

循环结束后。

也不要强制转换malloc的返回值。检查malloc的返回值以获得NULL检查并适当地处理它。

当乘以检查是否有溢出时。如果溢出处理它正确。


0
投票

好的,我发现了问题,我的for循环又做了一个b ++,它在我的字符串中创建了一个空单元格。

© www.soinside.com 2019 - 2024. All rights reserved.