【问题标题】:Getting garbage inside my string在我的字符串中获取垃圾
【发布时间】:2017-12-28 12:35:04
【问题描述】:

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

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


}

【问题讨论】:

  • 你确定size = len1*len2;?? + 还不够吗?
  • 无需转换malloc 的结果。了解 NULL 与 NUL 之间的区别。
  • @t0mm13b,哦,是的,它得到一个指向存储区域的指针并填充该存储区域。
  • @PaulOgilvie Woops..
  • 您的malloc() 也有问题,+ 1 放错地方了!这是您应该拥有的:newstr = (char*)malloc((size + 1) * sizeof(char));

标签: c string pointers malloc garbage


【解决方案1】:

你的问题

您将 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 检查并适当地处理它。

    同时在乘法时检查是否有溢出。在溢出的情况下正确处理。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 看看调试器会有多大用处?在您第一次尝试使用调试器单步执行代码时,您会发现问题;无需询问 Stack Overflow...:-)
      猜你喜欢
      • 1970-01-01
      • 2015-01-28
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      相关资源
      最近更新 更多