#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,请在我的代码中找到错误
最佳答案
您遇到段错误,因为 count
是 verify()
的局部变量函数以及对 verify()
的每次递归调用函数,count
初始化为0
和条件count<SIZE
永远是true
.
在每次递归调用 verify()
时,您正在通过k+1
并比较 k
处的元素数组的第一个位置 a
与 target
--> if(a[k]==target&&count<SIZE){....
。在某一阶段,k
将具有超出数组大小 a
的值。您的程序正在访问超出数组大小的元素,这是未定义的行为,其中包括程序可能会出现段错误。
您不需要count
根本没有变量。只需比较 k
的值即可与SIZE
以确保它不应该超出数组大小。
关于c - 条件递归中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379389/