由于这是常见的错误消息,因此我已在此问题上进行了搜索。不幸的是,我所能找到的都是线程,其中的问题源于名称相同的全局变量和局部变量。我的问题与全局变量无关,因此我认为这构成了一个新问题。 C不会让我调用函数。每次我调用这样的函数
...
adjusted_scores = *new_scores(scores,days_late,penalty);
numeric_score = final_score(adjusted_scores, weights);
...
,带有支持代码
int * new_scores(int scores[], int days_late[], int penalty) {
int new_scores[MAX_ASSIGNMENTS];
/*computes size of array*/
int size = sizeof(scores)/sizeof(scores[0]);
int i;
for(i=0;i<size;i++){
new_scores[i]=scores[i]-penalty*days_late[i];
}
return new_scores;
}
对于有问题的功能是否有帮助,我会收到消息
error: incompatible types when assigning to type 'int[50]' from type 'int'.
较早,我已经收到消息
error: called object 'new_scores' is not a function,
所以错误消息变得更长,并且情况没有得到改善。最重要的是,我一直收到消息警告我
warning: function returns address of local variable [enabled by default],
因此,即使我的错误消失了,实际运行代码的时候程序也可能以其他方式混乱。最好的情况是代码可以成功编译,但是该函数返回的任何内容都无法访问。
免责声明:由于无法解释的原因,不得使用malloc,memcpy和与动态内存分配相关的任何工具来解决此问题。我将尝试弄清楚如果免责声明成为太多负担以至于无法处理,这些原因是什么。
此错误消息:
error: incompatible types when assigning to type 'int[50]' from type 'int'.
告诉我们adjusted_scores
是一个数组,您不能直接分配给数组。
此警告:
warning: function returns address of local variable [enabled by default],
发生这种情况是因为函数new_scores
中的变量new_scores
是一个数组,并且在大多数情况下,数组会衰减为指向其第一个元素的指针,这意味着您正在返回局部变量的地址。这很不好,因为该变量在函数退出时超出范围,导致指针无效。
解决这两个问题的方法是将adjusted_scores
传递给该函数并将更新后的值直接分配给该函数。
此外,sizeof(scores)/sizeof(scores[0])
不会执行您期望的操作,因为scores
是指针,而不是数组,所以sizeof(scores)
是指针的大小。
所以new_scores
看起来像这样:
void new_scores(int result[], int scores[], int size, int days_late[], int penalty) {
int i;
for(i=0;i<size;i++){
result[i]=scores[i]-penalty*days_late[i];
}
}
您会这样称呼它:
new_scores(adjusted_scores,scores,sizeof(scores)/sizeof(scores[0]),days_late,penalty);