c - 警告传递 'finder' 的参数 2 使指针来自整数而不进行强制转换

标签 c compiler-errors

我正在尝试将用户输入的变量“find”传递给此函数并返回用户输入的数字(在现有数组中)的下标位置。我看到了一些关于此的其他帖子,但无法真正理解所解释的内容。对不起,初学者。

它不是很完整,但由于一些我不确定的错误,我无法编译。

  1. 警告传递“finder”的参数 2 使指针来自整数而不进行强制转换。它指向:

num_loc = finder(find, sort_num[10]);

这里我设置“num_loc”为函数中“where”的返回值 num_loc = finder(find, sort_num[10]); printf( "\n你的数字位于数组的内存位置 %d",num_loc );

  1. [注意] 需要 'int *' 但参数是 'int' 类型”,它指向我的函数原型(prototype)。

    //文件开头的main之外的fprototype int finder(int f,int x[]);

这是我的功能:

//function located at the end of the file outside the main
int finder(int f, int x[])
{
    int found = 0;
    int where;
    int i = 0;

    while (found != 1){
        if (x[i] == f){
            found = 1;
            where = i;
            return where;
        }
        else{
            ++i;
        }
    }
}

最佳答案

num_loc = finder(find, sort_num[10]);

相当于

int num = sort_num[10];       // Problem. Accessing array out of bounds.
num_loc = finder(find, num);  // Problem. Using an `int` when an `int*` is expected.
                              // That's what the compiler is complaining about.

您只需要在调用 finder 时使用 sort_num

num_loc = finder(find, sort_num);

真正的解决方案涉及更改 finder 以接受另一个参数,该参数指示 sort_num 中的元素数。否则,您将面临越界访问数组的风险。它也可以简化很多。

int finder(int f, int x[], int arraySize)
{
   for ( int i = 0; i < arraySize; ++i )
   {
      if (x[i] == f)
      {
         return i;
      }
   }

   // Not found
   return -1;
}

然后调用它:

num_loc = finder(find, sort_num, 10);

关于c - 警告传递 'finder' 的参数 2 使指针来自整数而不进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402327/

相关文章:

c - strlen 数组有不同的结果

c++ - c++中如何将字符串转换为string中提到的数据类型

c - 将 fseek 与指向标准输入的文件指针一起使用

c - 用 C 从文件中读取其中的所有元素

java - 为什么我在 Eclipse 中出现警告以及如何在最后导入时删除它 : The import java. sql.SQLException 从未使用过

c++ - 创建类对象时出错

c++ - 为什么编译器不显示这些返回类型的错误?

c# - 错误 : The Out Parameter must be assigned before control leaves the current method

c++ - 如何从客户端复制 http 服务器上的文件?

java - 使用javac编译时为"packaged does not exist"