我正在尝试将用户输入的变量“find”传递给此函数并返回用户输入的数字(在现有数组中)的下标位置。我看到了一些关于此的其他帖子,但无法真正理解所解释的内容。对不起,初学者。
它不是很完整,但由于一些我不确定的错误,我无法编译。
- 警告传递“finder”的参数 2 使指针来自整数而不进行强制转换。它指向:
num_loc = finder(find, sort_num[10]);
这里我设置“num_loc”为函数中“where”的返回值
num_loc = finder(find, sort_num[10]);
printf( "\n你的数字位于数组的内存位置 %d",num_loc );
[注意] 需要 '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/