如何在数组中找到缺少的值?
我试图使用功能检查找到数组中最小的缺失元素,该函数检查具有两个参数(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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编译器会调整具有数组类型的参数,以指向数组元素类型。
因此,此函数声明
等于
函数和内部的表达式
sizeof(a)
等效于expessionsizeof(int *)
,并且等于4或8在使用的系统上。因此,对于循环而言,这
会调用不确定的行为。
回答您的上述评论,似乎在使用的系统中
sizeof(int *)
等于8
,变量n
将阵列a
正如它们在MAIN中所定义的那样,您可以获得无限的Wile循环,因为在功能中的for循环中,已选中了变量
n
的内存,并且已检查代码> n 始终等于自身。因此,该功能始终返回
1
。那就是for循环中的数组,因为它具有8个元素,例如
The compiler adjusts a parameter having an array type to pointer to the array element type.
So this function declaration
is equivalent to
And within the function the expression
sizeof(A)
is equivalent to the expressionsizeof( int * )
and is equal to either 4 or 8 depending on the used system.Thus this for loop
invokes undefined behavior.
Answering your above comment it seems that in the used system
sizeof( int * )
is equal to8
and the variablen
is placed in memory after the arrayA
as they defined in mainAs 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 andn
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