C数组分配问题/CS50分数计算器



我试着用CS50学习C,并试着写一个考试成绩计算器。我试着写一个动态代码如下,但我得到了错误。这是我的主要代码:

#include <cs50.h>
#include <stdio.h>
const int total_exam = 3 ;  // Now we are creating a constant
//Prototype
//int get_scores(void);
int main(void)
{
// get exam scores
int *all_scores;
all_scores = get_scores();
printf("Your average score is %fn", average(total_exam, all_scores) );
}
// create an function to get exam scores of the user
int *get_scores()
{
//get exam scores of the user
int scores[total_exam];
for (int i=0;i< total_exam; i++)
{
scores[i] =  get_int("What's your exam score?: "); // each int uses 4 byte space
}
return scores;
}
// create an function to calculate average
float average(int length, int array[])
{
int sum=0;
for (int i=0 ; i<length; i++)
{
sum = sum+array[i];
}
return sum / (float) length ;
}

但当我尝试执行它时,我得到了如下错误。

scores_with_array.c:14:18: error: implicit declaration of function 'get_scores' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
all_scores = get_scores();
^
scores_with_array.c:14:16: error: incompatible integer to pointer conversion assigning to 'int *' from 'int' [-Werror,-Wint-conversion]
all_scores = get_scores();
^ ~~~~~~~~~~~~
scores_with_array.c:16:42: error: implicit declaration of function 'average' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
printf("Your average score is %fn", average(total_exam, all_scores) );
^
scores_with_array.c:16:42: error: format specifies type 'double' but the argument has type 'int' [-Werror,-Wformat]
printf("Your average score is %fn", average(total_exam, all_scores) );
~~     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%d
scores_with_array.c:22:6: error: conflicting types for 'get_scores'
int *get_scores()
^
scores_with_array.c:14:18: note: previous implicit declaration is here
all_scores = get_scores();
^
scores_with_array.c:33:12: error: address of stack memory associated with local variable 'scores' returned [-Werror,-Wreturn-stack-address]
return scores;
^~~~~~
scores_with_array.c:38:7: error: conflicting types for 'average'
float average(int length, int array[])
^
scores_with_array.c:16:42: note: previous implicit declaration is here
printf("Your average score is %fn", average(total_exam, all_scores) );
^
7 errors generated.

我想这是关于数组分配的,但我不明白。你能帮我解决这个问题吗?提前谢谢。

  1. 为什么您的get_scores原型会被注释?这导致了隐式声明问题。它也是错误的,应该是int *get_scores(void);
  2. average函数的原型不存在。C假定它返回一个int,这会导致更多的问题
  3. 为什么要返回scores数组,在函数退出后,堆栈会被破坏,并且可能发生内存泄漏。这样分配:int *scores = malloc(sizeof(int) * total_exam)

您的代码有点乱,所以如果问题继续存在,我不会感到惊讶。此外,请随时通过评论要求澄清。

最新更新