C语言调用better函数报整数转指针无强制转换警告问题
报错原因
test.c:47:45: warning: passing argument 1 of 'better' makes pointer from integer without a cast [-Wint-conversion]
test.c:6:16: note: expected 'int (*)[(sizetype)t]' but argument is of type 'int'
该报错核心由两个问题导致:
- 调用
better函数时传入的第一个参数是grades[num_of_students][t],这是尝试访问二维数组中某个具体位置的int类型元素,且该下标本身已经越界(二维数组行下标范围是0 ~ num_of_students-1,列下标范围是0 ~ t-1),完全不符合函数要求的参数类型。 better函数的参数顺序不符合C语言可变长数组的语法规则:数组参数中用到的长度参数num_of_students,需要定义在数组参数的前面,否则编译器无法正确识别数组长度。
修复方案
- 调用
better函数时,第一个参数直接传数组名grades即可,数组名作为参数传递时会自动退化为指向首元素的指针,刚好匹配int (*)[t]的参数类型要求。 - 调整
better函数的参数顺序,把num_of_students放在数组参数的前面。 - 可选优化:把全局变量
num_of_students改为main函数的局部变量,避免全局变量污染。
修改后的完整代码如下:
#include <stdio.h> const int t = 5; int better(int num_of_students, int grades[num_of_students][t]) { int i, k; int max = grades[0][0]; for (i = 0; i < num_of_students; i++) { for (k = 0; k < t; k ++) { if (grades[i][k] > max) { max = grades[i][k]; } } } return max; } int main(void) { int i, k; int num_of_students; printf("Give the number of students who took the test: "); scanf("%i", &num_of_students); int grades[num_of_students][t]; for (i = 0; i < num_of_students; i++) { printf("Student %i\n", i+1); for (k = 0; k < t; k++) { printf("Give the score on test %i: ", k+1); scanf("%i", &grades[i][k]); while (grades[i][k] < 0 || grades[i][k] > 100) { printf("Not an acceptable score, try again %i: ", k+1); scanf("%i", &grades[i][k]); } } } int max = better(num_of_students, grades); printf("The best score is %i\n", max); return 0; }
内容的提问来源于stack exchange,提问作者faelex
相关产品推荐
相关产品推荐

