使用void函数计算C中数组中最常见的整数

lem*_*yer 3 c arrays element counting

你好!我正在尝试创建一个程序(学校作业),要求用户输入0到1000之间的整数序列.当用户输入负整数或超过100个整数时,序列停止.

实际上输入,保存和创建一个"计数器"数组,其中包含输入整数的次数.但是,赋值的一部分是创建一个void函数,该函数使用指针变量来返回最多次出现的整数以及出现的次数.

#include <stdio.h>
#include <stdlib.h>

#define MAX_SEQ 100

void analyzeFrequencies(int mainArray[], int counter[], int* mOI, int* numOfOccurences);

int main()
{
    int i=0, *mOI=0, *numOfOccurences=0, tempNum=0, mainArray[MAX_SEQ] = {0}, counter[MAX_SEQ] = {0};

    printf("Please enter a integer between 0-1000.\nSequence will stop when you enter negative integer of after MAX_SEQ integers.\n\n");

    do
    {
        if( scanf("%d", &tempNum) == 1)
        {
            if (tempNum <= 1000)
            {
                if (tempNum < 0)
                {
                    printf("You decided to exit the sequence. Your array entered is:\n");
                }
                else
                {
                    mainArray[i] = tempNum;
                    counter[tempNum]++;
                    ++i;
                }
            }
            else
                printf("Please enter a number between 0-1000. Exit sequence by entering negative number.\n");
        }
        else
            printf("\nError.\n");

    } while(tempNum > 0 && i < MAX_SEQ);

    analyzeFrequencies(mainArray, counter, mOI, numOfOccurences); //This is where the problem occurs.

    if (i == 0)
    {
        printf("You entered no sequence.");
    }
    else
    {
        printf("\nSequence:\n");
        for(int j=0; j<i; j++)
        {
            printf("[%d] %d\n", j, mainArray[j]);
        }

        printf("Most occurred item: %d\nOccurred %d times!", *mOI, *numOfOccurences);
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行我的代码时,一切正常,直到我执行analyzeFrequencies()函数.该程序然后停止工作.

void analyzeFrequencies(int mainArray[], int counter[], int* mOI, int* numOfOccurences)
{
    for(int i=0; i<MAX_SEQ; i++)
    {
        if(counter[i] > *numOfOccurences)
        {
            *mOI = i;
            *numOfOccurences = counter[i];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望函数"void analyzeFrequencies"通过"mOI"和"numOfOccurences"返回一个指针变量值.mOI是发生最多的整数.

相反,该程序停止工作.我一直在看我的代码一段时间,但似乎无法找到导致这种情况的原因.我的代码可能已经坐了很长时间并且失明了.会有任何帮助,以实现我的错误!

PS!我意识到代码根本没有优化,我很乐意收到任何反馈,但我的主要优先事项是使analyzeFrequencies功能开始工作!

dbu*_*ush 5

int i=0, *mOI=0, *numOfOccurences=0, tempNum=0, 
    mainArray[MAX_SEQ] = {0}, counter[MAX_SEQ] = {0};
Run Code Online (Sandbox Code Playgroud)

在你的main函数中,你已经mOInumOfOccurences声明为指针变量,它们都被初始化为0,这意味着它们是NULL指针.然后,将这些NULL指针传递给您的函数并取消引用它们.取消引用NULL指针会调用未定义的行为.

声明这两个变量int,而不是int *和通过他们的地址analyzeFrequencies.

所以声明他们是这样的:

int i=0, mOI=0, numOfOccurences=0, tempNum=0, 
    mainArray[MAX_SEQ] = {0}, counter[MAX_SEQ] = {0};
Run Code Online (Sandbox Code Playgroud)

并调用你的函数:

analyzeFrequencies(mainArray, counter, &mOI, &numOfOccurences)
Run Code Online (Sandbox Code Playgroud)