警告传递' finder'的参数2从没有强制转换的整数生成指针

时间:2015-10-28 21:57:36

标签: c compiler-errors

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

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

  1. 警告传递' finder'的参数2从没有强制转换的整数生成指针。它指着:
  2. num_loc = finder(find, sort_num[10]);

    我在这里设置" num_loc"回归"其中"在功能中      num_loc = finder(find, sort_num[10]); printf( "\nYour number is located in memory location %d of the array",num_loc );

    1. " [注意]预期' int *'但参数的类型为' int'"这是指向我的函数原型。

      //fprototype outside the main at the beginning of the file int finder(int f,int x[]);

    2. 这是我的功能:

      //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;
              }
          }
      }
      

2 个答案:

答案 0 :(得分:2)

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.

您需要在sort_num的调用中使用finder

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);

答案 1 :(得分:1)

这是函数定义的第一部分:

int finder(int f, int x[])

你的第二个参数是一个int指针,编译器告诉你的是:

expected 'int *'

你用这个来调用你的函数:

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

如果sort_num是整数数组,则sort_num [10]计算为该数组中第11位的整数。所以你将finder函数传递给整数,而不是int指针。如果sort_num是一个整数数组,请将您的调用重写为:

num_loc = finder(find, sort_num);

这样你就会传递一个int指针,它保存sort_num数组中第一个元素的地址。

相关问题