c - 在代码块 IDE 中获取垃圾值作为我的搜索值

标签 c codeblocks

我正在 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”。请看下图

enter image description here

我的问题是 i=5 ,为什么我会“找到”。为什么它不是“垃圾值(value)”?

最佳答案

主要问题是由于i<=5,您正在越界访问数组。 。此检查允许 i成为5 ,但是使用 的数组索引从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/

相关文章:

c - pthread_cancel 在 solaris 下不工作

指针和整数之间的c strptime警告比较

c - 又一个 "x"没有命名类型错误

c++ - 代码块: 'Class' 未在此范围内声明

c - 通过 glfw 或 lungarg 为 code::blocks 设置 vulkan

c - GTK+/GCC 启动时崩溃

c - 关于C循环的问题

c++ - 代码块 "Other Linker Options"翻译 "Link Libraries"和库包含效率

c - 为什么我的程序是单步执行而不是正常执行?

codeblocks - 如何在代码块中缩进我的代码?