【问题标题】:passing argument 1 of 'better' makes pointer from integer without a cast传递“更好”的参数 1 使指针从整数而不进行强制转换
【发布时间】: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 &gt; 1 ? strtoul(argv[1], NULL, 10) : 1; ...

标签: c arguments function-call variable-length-array incompatibletypeerror


【解决方案1】:

对于初学者来说,改变函数声明

int better(int grades[num_of_students][t], int num_of_students)

int better(int num_of_students, int grades[num_of_students][t] )

否则不清楚是在第一个参数int grades[num_of_students][t]的声明中使用了全局变量num_of_students还是第二个参数的标识符。那就是函数声明,它会让代码的读者感到困惑。

然后这样称呼它

int max = better( num_of_students, grades );

否则,您将尝试传递 int 类型的数组 grades[num_of_students][t] 中不存在的元素,而不是数组本身。

【讨论】:

  • 在 GCC 或 CLANG 中,可以对参数进行前向声明。所以可以使用:int better(int num_students; int grades[num_of_students][t], int num_of_students) ,然后调用better(arr, num_of_students)
猜你喜欢
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多