我的程序锁定,似乎没有做它应该做的事情。我做错了什么?

时间:2022-09-20 18:57:41

I'm a newbie to C programming and I'm up to learning about strings and arrays. My latest challenge is to read in a string, calculate the frequency of each letter and output these including non-letters.

我是C编程的新手,我正在学习字符串和数组。我最近的挑战是读取一个字符串,计算每个字母的频率并输出这些字母,包括非字母。

I've written the program but it either locks up or just stops. I can't get it to start the count. Where have I gone wrong?

我已经编写了程序,但要么锁定要么停止。我无法让它开始计算。我哪里出错了?

NB: My lecturer has some particular views on syntax that other people don't necessarily share. I'm going to stick with the syntax that's going to keep my lecturer happy so please don't pick on the "return (0);" at the end of the main function.

注意:我的讲师对其他人不一定分享的语法有一些特别的看法。我将坚持使我的讲师开心的语法,所以请不要选择“return(0);”在主要功能的最后。

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

const int COUNT = 27;
const int STRSIZE = 100;

                counter[c]++;
                c++;
            }
            else 
                if((letterfreq[i] < 'a') || (letterfreq[i] > 'z'))
                {   
                    counter[26]++;
                }
        }
    }

    return;
}

void printFreq(int counter[], int COUNT)
{
    int c;

    in the string.\n", counter[26]);

    return;
}

char promptReset(char reset)
{
    printf("Would you like to calculate the letter frequency of another string? (Y/N)\n");
    scanf("%c%*c", &reset);

    tolower(reset);

    return(reset);
}

int main()
{

1 个解决方案

#1


In your code,

在你的代码中,

 tolower(letterfreq[STRSIZE]);

is overruning allocated memory, which in turn invokes undefined behaviour. Remember, C array index is 0 based.

超出分配的内存,反过来调用未定义的行为。记住,C数组索引是基于0的。

That said,

  1. I don't see the point of the whole statement here. Maybe you'd want to have a look at the man page of tolower(http://linux.die.net/man/3/tolower) one again.

    我没有在这里看到整个陈述的重点。也许你想再看一下tolower(http://linux.die.net/man/3/tolower)的手册页。

  2. There is no need to pass COUNT, STRSIZE as arguments to functions.

    不需要将COUNT,STRSIZE作为参数传递给函数。

#1


In your code,

在你的代码中,

 tolower(letterfreq[STRSIZE]);

is overruning allocated memory, which in turn invokes undefined behaviour. Remember, C array index is 0 based.

超出分配的内存,反过来调用未定义的行为。记住,C数组索引是基于0的。

That said,

  1. I don't see the point of the whole statement here. Maybe you'd want to have a look at the man page of tolower(http://linux.die.net/man/3/tolower) one again.

    我没有在这里看到整个陈述的重点。也许你想再看一下tolower(http://linux.die.net/man/3/tolower)的手册页。

  2. There is no need to pass COUNT, STRSIZE as arguments to functions.

    不需要将COUNT,STRSIZE作为参数传递给函数。