c - 条件递归中的段错误

标签 c recursion

#include<stdio.h>

#define SIZE 5

void verify(int a[],int,int);

int main()
{
    int a[SIZE],target,k=0;
    printf("enter the array elemans:\n");

    for(int i=0;i<SIZE;i++)
        scanf("%d",&a[i]);

    printf("enter the target :\n");
    scanf("%d",&target);

    verify(a,target,k);
    return 0;
}

void verify(int a[],int target,int k)
{
    int count=0;
    if(a[k]==target&&count<SIZE)
    {
        printf("target found:%d at index= %d\n",a[k],k);
        verify(a,target,k+1);
        count+=1;
    }
    else if(count<SIZE)
    {
        verify(a,target,k+1);
        count+=1;
    }
    else 
    {
        printf("target not found !!!");
    }
}

当我尝试查找不在列表/数组中的数字时,我没有执行 else 语句,而是显示段错误 11,请在我的代码中找到错误

最佳答案

您遇到段错误,因为 countverify() 的局部变量函数以及对 verify() 的每次递归调用函数,count初始化为0和条件count<SIZE永远是true .
在每次递归调用 verify() 时,您正在通过k+1并比较 k 处的元素数组的第一个位置 atarget --> if(a[k]==target&&count<SIZE){.... 。在某一阶段,k将具有超出数组大小 a 的值。您的程序正在访问超出数组大小的元素,这是未定义的行为,其中包括程序可能会出现段错误。

您不需要count根本没有变量。只需比较 k 的值即可与SIZE以确保它不应该超出数组大小。

关于c - 条件递归中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379389/

相关文章:

c - C 中的 open() 系统调用以字符数组作为附加路径?到文件名

recursion - 计算句子中奇数的个数

c - 指向自身的指针

c - memset 未填充数组

python - 递归累积或如何计算 Python 中的递归调用次数?

algorithm - 我应该使用什么算法来解决 "shortest path problem"?

c - 在C中实例化临时静态列表头指针

c# - 带任务的尾递归?

未知文件类型的 C 文件输入/输出 : File Copying

c - 访问填充有从管道读取的数据的结构时出现段错误