【发布时间】:2021-11-01 07:28:46
【问题描述】:
这是一个相当简单的程序,它找到二维数组等级的最大元素并将其打印到屏幕上
#include <stdio.h>
const int t = 5;
int num_of_students;
int better(int grades[num_of_students][t], int num_of_students)
{
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;
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(grades[num_of_students][t], num_of_students);
printf("The best score is %i\n", max);
}
然而,当我尝试运行程序时,会弹出以下错误: test.c:47:45:警告:传递“更好”的参数 1 使指针从整数而不进行强制转换 [-Wint-conversion] test.c:6:16:注意:预期为 'int (*)[(sizetype)t]' 但参数的类型为 'int'
【问题讨论】:
-
better(grades[num_of_students][t]->better(grades。因为你想传递grades的整个数组。grades[num_of_students][t]是单个元素(并且是越界元素)。 -
不要从标准输入读取参数,将它们作为参数传递:
int main(int argc, char **argv) { int num_of_students = argc > 1 ? strtoul(argv[1], NULL, 10) : 1; ...
标签: c arguments function-call variable-length-array incompatibletypeerror