c - c 程序崩溃

标签 c

我的代码似乎每次运行时都会崩溃,我想编写一个程序来查找句子中的大写字母(str[max]),并打印出找到它的次数

我从构建日志中收到警告(警告:在此函数中可能会使用未初始化的“c”)(这里非常入门级程序员!!)

#include <stdio.h>
#include <string.h>
#include "genlib.h"
#include "simpio.h"
#include "ctype.h"


#define max 26

void checktimes(char str[],char temp);

int main()
{
char str[max], temp;
printf("Type a sentence with 25 characters max :");
gets(str);

int i;
for(i=0;i<=max;i++)
{
temp = str[i];
 if(isupper(temp))
    checktimes(str,temp);
}
 return 0;
}

void checktimes(char str[],char temp)
{
int j,i;
char c;
for(j=0; j<=max ; j++)
{
    str[i] = c;
    if(c == temp)
        i++;
}
printf("%c --> %d",temp,i);

}

最佳答案

您有多个问题:

1) 切勿使用 gets() 。使用fgets()相反。

2) 你可能并不总是有max字符数。所以,你的情况:for(i=0;i<=max;i++)可能是错误的。 使用strlen()找出 str 中的实际字符数.

3) 您正在阅读c此处未初始化:

str[i] = c;

您的意思可能是:

c = str[j]; /* notice the i -> j change */

4) isupper() 的参数需要强制转换为 unsigned char .

5) 初始化i0checktimes() .

<小时/>

事实上,这也存在逻辑错误。您将多次打印重复字符的计数。 如果使用临时数组,可以写成:

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

#define max 26

void checktimes(char str[]);

int main(void)
{
    char str[max];
    printf("Type a sentence with 25 characters max :");
    fgets(str, sizeof str, stdin);
    str[strcspn(str, "\n")] = 0; /* To remove the trailing newline if any. */
    checktimes(str);
    return 0;
}

void checktimes(char str[])
{
    int i = 0;
    int count[max] = {0};
    size_t len = strlen(str);
    for(i=0; i<len; i++)
    {
        if(isupper((unsigned char)str[i]))
            count[str[i] - 'A']++;
    }
    for(i = 0; i < max; i++)
    if (count[i])
        printf("%c --> %d\n",i+'A', count[i]);
}

关于c - c 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42008794/

相关文章:

Python C API 和数据持久保存在内存中?

c - C语言中的"too many arguments to function"

python - SWIG C 到 Python 整数数组

c++ - 伐木礼仪

c - 将 tcmalloc 与 glib 结合使用

c - 如何忽略 fscanf() 中的空格

python - 将数独解算器从 C 移植到 Python 时出现问题

c - 为什么我以后不能更改字符数组?

c - Klocwork 是否检测到从未调用过的函数?

c++ - string.h 和 cstring 之间的区别?