c++ - 函数和指针帮助 : Program builds but Crashes without any specific errors

标签 c++ c

我正在处理一项硬件分配,并且不断发生崩溃,但我没有收到任何错误,它只是崩溃了。我创建了 2 个函数来尝试计算最大值、最小值和平均值,并创建了 1 个函数来生成 3 个随机数并将其发送回主函数。我的函数中的所有值都需要作为指针返回。感谢您的提前帮助!

int * random_number()
{
     static int num[3];
     for(int i = 0; i < 3; i++){

         num[i] = (10 + rand() % 90);
     }
     return num;
}

int * calculate(int *value)
{
    static int ans[3];
    int max = 0;
    for (int i = 0; i < 3; i++)
    {
        ans[0] += value[i];
        ans[0] = ans[0] / i;
        if (value[i] > max)
        {
            ans[2] = max;
        }
        int min = value[0];
        if (value[i] < min)
        {
            ans[3] = min;
        }
    }
    return ans;

}



int main() {

    srand(time(NULL));
    int cnt = 0;
    int *result;
    int *find;

    do{
        result = random_number();
        find = calculate(result);
        cnt++;
    }


    while(cnt < 10);
        if (cnt == 10){
            printf("Result is %i, %i, %i.", result[0],result[1],result[2]);
            printf("The avg is %i. The max is %i and the min is %i.", find[0], find[1], find[2]);

            printf("Worked \n");
        }
        else
            printf("Didn't work");


    return 0;
}

最佳答案

您的 calculate() 函数有许多错误 - 主要是您试图在 for 循环内执行一些本应在其外部执行的操作。您遇到的崩溃来自以下行:

        ans[0] = ans[0] / i;

...当第一次循环中 i 为零时(因此除以零)。该除法实际上应该在循环之后、所有值都被添加之后完成(并且始终除以 3)。

行:

         int min = value[0];

也应该移到循环之前;事实上,您在每次循环时都会重置 min 的值,因此实际上最终会得到小于 value[ 的 last 值0],如果有的话......并且当没有时你根本不改变ans[3]。无论如何,ans[3]实际上应该是ans[2]...ans[3]超出范围(将是第四个元素) )。

关于c++ - 函数和指针帮助 : Program builds but Crashes without any specific errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49711066/

相关文章:

c++ - 将类型映射到整数值后,如何获得给定整数值的类型?

c - 将列表传输到类(class)

c - 仅保留数据结构的少量更改

c++ - 编译程序以在 DOS 模式下运行

c++ - 具有定义的友元函数 - 模板还是非模板?

c - 在将指针传递给外部库方法后释放内存时 RtlFreeHeap 无效地址

c - 为什么for循环没有被执行?(线性搜索)

c - 从 Fortran 运行时 METIS 段错误

c++ - 测量内存的潜伏期

c++ - 如何实现具有多个键的快速 map ?