c语言 - 警告传递"finder"的参数 2 从整数生成指针而不进行强制转换



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

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

  1. 传递"finder"的参数2的警告使指针从整数变为不带强制转换。它指向:

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

在这里,我将"num_loc"设置为函数中"where"的返回 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[]);

这是我的功能:

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

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

int finder(int f, int x[])

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

expected 'int *'

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

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

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

num_loc = finder(find, sort_num);

通过这种方式,您将传递一个int指针,该指针保存sort_num数组中第一个元素的地址。

最新更新