如何在数组中找到缺少的值?

发布于 2025-01-28 17:57:17 字数 463 浏览 3 评论 0原文

我试图使用功能检查找到数组中最小的缺失元素,该函数检查具有两个参数(N和Array A)。我不明白为什么我的功能检查总是返回一个,而while循环永远不会关闭。

#include <stdio.h>

bool check(int n, int A[])
{
    for (int i = 0; i < sizeof(A); i++)
    {
        if(A[i] == n) 
        {
            return 1;
        }
    }
    return 0;
}

int main()
{
    int A[] = {1, 3, 6, 4, 1, 2};
    int n = 1;

    while (check(n, A) == 1)
    {
        n++;
    }
        
    printf("%d is missing",n);
}

I am trying to find the smallest missing element of an array using function check, which has two arguments (n and array A). I can't understand why my function check is always returning one and the while loop is never closing.

#include <stdio.h>

bool check(int n, int A[])
{
    for (int i = 0; i < sizeof(A); i++)
    {
        if(A[i] == n) 
        {
            return 1;
        }
    }
    return 0;
}

int main()
{
    int A[] = {1, 3, 6, 4, 1, 2};
    int n = 1;

    while (check(n, A) == 1)
    {
        n++;
    }
        
    printf("%d is missing",n);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的背包 2025-02-04 17:57:17

编译器会调整具有数组类型的参数,以指向数组元素类型。

因此,此函数声明

bool check(int n, int A[])

等于

bool check(int n, int *A );

函数和内部的表达式sizeof(a)等效于expession sizeof(int *) ,并且等于4或8在使用的系统上。

因此,对于循环而言,这

for (int i = 0; i < sizeof(A); i++)

会调用不确定的行为。

我知道,但这仍然不是为什么while循环永远不会停止的原因。

回答您的上述评论,似乎在使用的系统中sizeof(int *)等于8,变量n将阵列a正如它们在MAIN中所定义的

int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;

那样,您可以获得无限的Wile循环,因为在功能中的for循环中,已选中了变量n的内存,并且已检查代码> n 始终等于自身。

因此,该功能始终返回1

那就是for循环中的数组,因为它具有8个元素,例如

int A[] = {1, 3, 6, 4, 1, 2, n, some_indeterminate_value };

The compiler adjusts a parameter having an array type to pointer to the array element type.

So this function declaration

bool check(int n, int A[])

is equivalent to

bool check(int n, int *A );

And within the function the expression sizeof(A) is equivalent to the expression sizeof( int * ) and is equal to either 4 or 8 depending on the used system.

Thus this for loop

for (int i = 0; i < sizeof(A); i++)

invokes undefined behavior.

I know but still that's not why the while loop is never stopping.

Answering your above comment it seems that in the used system sizeof( int * ) is equal to 8 and the variable n is placed in memory after the array A as they defined in main

int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;

As a result you get the infinite wile loop because in the for loop within the function the memory occupied by the variable n is checked and n is always equal to itself.

Thus the function always returns 1.

That is in the for loop the array is traversed as it has 8 elements like

int A[] = {1, 3, 6, 4, 1, 2, n, some_indeterminate_value };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文