代码在 C 中未按预期工作

标签 c arrays fgets strcat

我正在用 C 编写一个程序来计算句子中的空格数。但我没能让它正常工作。如果我输入类似 Hello world 1234 how are you 的内容,当预期输出为 5 时,我得到的输出为 3。
我的代码是:

//Program to count number of words in a given Sentence
#include <stdio.h>
#include <string.h>
int main()
{
    char sent[100];
    char sentence[] = {' ', '\0'};
    printf("\nEnter a sentence :\n");
    gets(sent);
    strcat(sentence, sent);
    int l = strlen(sentence), i = 0, count = 0, countCh = 0;
    printf("%d", l);
    char ch, ch1;
    for (i = 0; i < (l-1); i++)
    {
        ch = sentence[i];
        if (ch == ' ')
        {
            ch1 = sentence[i+1];
            if (((ch1 >= 'A') && (ch1 <= 'Z'))||((ch1 >= 'a') && (ch1 <= 'z')))
                count++;
        }
    }
    printf("\nNo of words is : %d", count);
    return 0;
}

我在 Java 中使用了相同的逻辑,并且运行良好。谁能解释一下出了什么问题?

最佳答案

您的代码中的问题在于 sentence 的定义。当您省略数组维度并对其进行初始化时,数组的大小将由初始化程序的长度决定。

引用man page strcat()

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable;

也就是说,程序将调用undefined behavior .

这样,sentence 的内存肯定比它应该容纳的要少得多。此外,strcat() 根本不是必需的

正确的做法是

  • 用适当的维度定义sentence,比如char sentence[MAXSIZE] = {0};,其中MAXSIZE将是一个宏您选择的尺寸。
  • 使用 fgets() 读取用户输入。
  • 使用isspace() (来自 ctype.h)在一个循环中检查输入字符串中是否存在空格。

关于代码在 C 中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36885634/

相关文章:

c - 如果我声明一个 10 元素数组并尝试访问其中更大的位置,到底会发生什么?

Java : Testing Array Sum Algorithm Efficiency

javascript - 为什么不在数组中添加元素?

c - fork 和 exec 的区别

c - 为什么编译器找不到头文件?

c - C中的接口(interface)交互

c - 关于在c中使用fgets和scanf读取输入的问题

c - fgetc内部如何工作

c - 使用 fgets 时忽略多余的空格

c - 显示静态和动态分配之间差异的 C 代码