我正在 code::blocks IDE 中尝试简单的线性搜索,我的编码如下
int main(){
int numbers[5] = {2,10,20,60,40},search = 60,i=0;
for(i=0;i<=5;i++){
printf("%d ",numbers[i]);
if(numbers[i]==search){
printf("Index[%d] : Found\n",i);
//break;
}else{
printf("Index[%d] : Not Found\n",i);
}
}
return 0;
}
如果我没有使用条件中断并且保留 i<= 5 ,则它比数组大小更大。对于 i=3 和 i=5,我得到输出“Found”。请看下图
我的问题是 i=5 ,为什么我会“找到”。为什么它不是“垃圾值(value)”?
最佳答案
主要问题是由于i<=5
,您正在越界访问数组。 。此检查允许 i
成为5
,但是使用 c 的数组索引从0
开始至size-1
。所以允许的最大索引是 4
.
#include <stdio.h>
int main(void)
{
int numbers[] = { 2, 10, 20, 60, 40 };
int search = 60;
for (size_t i = 0; i < sizeof(numbers)/sizeof(numbers[0]); i++)
{
printf("%d ", numbers[i]);
if (numbers[i] == search)
{
printf("Index[%zu] : Found\n", i);
//break;
}
else
{
printf("Index[%zu] : Not Found\n", i);
}
}
return 0;
}
如您所见,我还更改了 for
使用sizeof(numbers)/sizeof(numbers[0]);
如果您更改它,它会授予该代码自动使循环适应数组的实际大小。
最后我改变了i
类型由于 sizeof
返回类型为 size_t
:正确printf
size_t
的格式格式说明符类型是%zu
。
编辑
尝试解释原因 "Found"
在这种特定情况下打印,我们可以看到变量是如何分配的
-----------------------------------------------------------------
| array[0] | array[1] | array[2] | array[3] | array[4] | search |
-----------------------------------------------------------------
^
|
------------
| array[5] |
------------
所以当您访问array[5]
时,您实际上正在访问 search
的值变量,即60
。所以
if(numbers[i]==search)
可以看作
if(search==search)
这显然是true
.
关于c - 在代码块 IDE 中获取垃圾值作为我的搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42923143/