如果找到数字,我尝试打印 1;如果未找到,则打印 0。
我的代码 int search(int a[], int n, int key, int **loc) 查找数组并返回 0 或 1。
但是,当我运行它时,我得到了 4195632。
我认为该数字与地址有关,但不知道我做错了什么
a[5] 是数组
n = 数组的大小
key是我要寻找的元素
**loc 应该是指向数组中搜索键的第一个位置的指针
#include <stdio.h>
int a[5] = {5,3,7,2,9};
int n = 5;
int key = 5;
int **loc = 0;
int search(int a[], int n, int key, int **loc)
{
int x;
for(x = **loc; x < n; x++)
{
if(a[x] == key)
{
return 1;
}
else
return 0;
}
return 0;
}
int main()
{
printf("%d\n",search);
}
而且我不确定 **loc 是做什么的。我知道它与指针有关,但我想我必须使用它,因为这是家庭作业。
最佳答案
您的意思似乎如下。
#include <stdio.h>
int search( const int a[], size_t n, int key, size_t *loc )
{
*loc = 0;
while ( *loc < n && a[*loc] != key ) ++*loc;
return *loc != n;
}
int main(void)
{
int a[] = { 5, 3, 7, 2, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
int key = 5;
size_t loc;
if ( search( a, N, key, &loc ) )
{
printf( "%d is found at position %zu\n ", key, loc );
}
return 0;
}
程序输出为
5 is found at position 0
如果最后一个参数必须具有类型int **
,那么该函数可以如下所示
#include <stdio.h>
int search( const int a[], size_t n, int key, int **loc )
{
*loc = ( int * )a;
while ( *loc != a + n && **loc != key ) ++*loc;
return *loc != a + n;
}
int main(void)
{
int a[] = { 5, 3, 7, 2, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
int key = 5;
int *loc;
if ( search( a, N, key, &loc ) )
{
printf( "%d is found at position %zu\n ", key, ( size_t)(loc - a) );
}
return 0;
}
很奇怪,但输出与上面的程序相同
5 is found at position 0
关于c - 尝试根据数字是否在数组中打印 1 或 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44478974/