c - 尝试根据数字是否在数组中打印 1 或 2

标签 c arrays algorithm search

如果找到数字,我尝试打印 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/

相关文章:

java - 从数组中打印值时出现 ArrayIndexOutOfBoundsException

JavaScript Array.sort 不适用于某些数字数组

string - 有效地计算一个字符串和一大组其他字符串之间的编辑距离?

jquery - 检查两个数组的值是否相等

python - 查找字符串中最长的重复序列

c - 如何找到每个大小为 n 的 m 个数组的最长公共(public)子数组?

c++ - OpenMP 任务和 Taskwait 构造

c - 使用 getopt 在 C 中解析参数

c - Strcmp 生成核心转储

android - 是否可以配置 GCC 为 android 进行编译?