C正在打印不需要的随机字符

时间:2018-04-06 12:50:55

标签: c arrays debugging

我在C中编写了一些代码,它的作用是输入2个字符串A,B其中A是普通字符串,B是B字符串中的子字符串。程序将“剪掉”所有外观字符串A内的子标记B.例如:

A =“asdLEONasd”,B =“asd”=> C(结果)=“LEON”。
除了在输出阶段打印出一些不需要的字符之后,一切似乎都工作正常。

这里有两个例子:(不需要的字符用红笔加下划线)

Example 1

Example 2

代码:

#include <stdio.h>
#include <string.h>

void main()
{
    int len1, len2;

    puts("Input a length for a");
    scanf("%d",&len1);
    // Initializing A
    char a[len1 + 1];
    puts("Input a");
    scanf("%s" ,a);

    puts("Input length for b");
    scanf("%d",&len2);
    //Initializing B
    char b[len2 + 1];
    puts("Input b");
    scanf("%s" ,b);

    int i, j , k, count1 = 0, count2;

    for(i = 0; i < len1; i++) //Loop that goes over string a
    {
        count2 = 0, k = 0;
        for(j = i; j < len2 + i; j++) //Loop that goes over a part of a (from i to i + len2)
        {
            if(a[j] == b[k])
            {
                count2++; //Counting how many characters match with the sub string B
            }
            k++;
        }
        if(count2 == len2) //If counted characters = len2 then we know that we found the Sub string B in A
        {
            count1++; //Counting each appearance of B in A
            for(j = i; j < len2 + i; j++) //Loop that marks cells that represent the sub string B in A
            {
                a[j] = '0'; //Marking cells that are the sub string b
            }
        }
    }

    if(!count1) //If count1 remained as 0 then B does not appear in A, which means the result is A
    {
        puts(a);
    }
    else
    {
        j = 0;
        int len3 = len1 - count1 * len2; //Determining resulting array size
        char c[len3]; // Initializing array C
        //Filling array C accordingly
        for(i = 0; i < len1; i++)
        {
            if(a[i] != '0')
            {
                c[j] = a[i];
                j++;
            }
        }
        puts(c);
    }
}

我觉得最奇怪的是当我的输出数组的大小为4时,无论大小如何,它仍会打印额外的字符。
我很好奇为什么会发生这种情况以及如何解决?

3 个答案:

答案 0 :(得分:1)

你应该想到puts的愚蠢实现如下:

void puts(char *s)
{
  while (*s) //if the current character isn't 0
  {
    putchar(*s); //print the character
    ++s; //move to the next character
  }
  putchar('\n');
}

因此,如果数组中的最后一个字符不是0,则上述循环将继续,直到后续内存中某处出现0为止。

如果您无法添加此终止零(正如Bathsheba和您自己所提到的那样),您可以使用printf

使用printf系列函数时,可以使用%s说明符格式化字符串(例如填充并限制它的长度)。

char x[] = {'a', 'b', 'c', 'd'};
//print just abc
printf("%.*s\n", 3, x);
//print just abc
printf("%.3s\n", x);
//print just bcd
printf("%.*s\n", 3, x+1);

答案 1 :(得分:0)

问题在于数组C. 将char c[len3];更改为char c[len3 + 1];并添加初始化c[len3] = '\0';已修复此问题。

答案 2 :(得分:0)

在程序倒数第三行之前,正好在这句话puts(c)前面,如果你添加c[j]='\0',你说的问题就会解决。