【问题标题】:Warning passing argument 2 of 'finder' makes pointer from integer without a cast警告传递 'finder' 的参数 2 使指针从整数而不进行强制转换
【发布时间】:2015-10-28 21:57:36
【问题描述】:

我正在尝试将用户输入的变量“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. "[Note] 预期为 '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;
        }
    }
}

【问题讨论】:

  • 我觉得自己很愚蠢......就是这样......谢谢......
  • int x[] 是一个int *(在此上下文中是一个指针或数组)。你用sort[10] 调用它,这可能是一个int,所以警告是合乎逻辑的:你从一个整数值(你给的sort[10])创建一个指针(需要int*)。
  • question/printf() 语句中的“内存中的位置”似乎表示内存地址,但是,%d 用于打印整数。要打印地址,请使用:%p

标签: c compiler-errors


【解决方案1】:
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);

【讨论】:

  • 好的。除了在传递的数组中找不到数字之外,似乎还在运行。不过,我认为这本身可能是另一个问题。
【解决方案2】:

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

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 数组中第一个元素的地址。

【讨论】:

  • 感谢您的帮助!每个人都非常乐于助人。
猜你喜欢
  • 2015-05-30
  • 2019-09-17
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2019-02-18
相关资源
最近更新 更多