为什么当我的输入超过 5 时会出现分段错误?

问题描述 投票:0回答:1

所以我已经在第 2 周完成了小时练习题,但每当我输入的数字(第一个提示)超过 5 时,我就会遇到分段错误。

#include <cs50.h>
#include <stdio.h>

int N = 0;

int total(int array[]);
float average(int array[]);

int main(void)
{
    // to prompt the me to input whatever week i'm in then loop a get_int to ask the hours i spent on each week
    int score[N];
    N = get_int("Number of weeks taking CS50: ");

    int hours = 0;

    for (int i = 0; i < N; i++)
    {
        score[i] = get_int("Week %i hours: ", hours);
        hours++;
    }

// to prompt the me in picking if i want a totsl or avg

    char result;
    do
    {
        result = get_char("Enter T for total hours, A for average: ");
    }
    while (result != 'T' && result != 'A');

    if (result == 'T')
    {
        printf("%i hours\n", total(score));
    }
    else if (result == 'A')
    {
        printf("%f hours\n", average(score));
    }
}


// functions to compute what they said on their names

int total(int array[])
{
    int sum = 0;
    for (int j = 0; j < N; j++)
    {
        sum = sum + array[j];
    }
    return sum;
}

float average(int array[])
{
    int sum = 0;
    for (int a = 0; a < N; a++)
    {

注意:我为此使用 cs50 vscode 代码空间。到目前为止,这是我在此代码中看到的唯一错误,因此请让我知道您的意见和指导。尽可能明目张胆。

arrays c segmentation-fault
1个回答
-2
投票

您已使用

将分数设置为零大小的数组
int score[N];

然后你使用

更改了N
N = get_int("Number of weeks taking CS50: ");
即使您更改了 N,

score 仍然是零大小的数组。 您应该使用:

  • int 分数[100]; // 例如。假设 100 高于您可以获得的最大 N。
  • score = malloc(N*sizeof(int)) // 设置 N 后
© www.soinside.com 2019 - 2024. All rights reserved.