I want to find the address of an integer in an array. Debugger revealed that line 8 is at fault.
if (*i==item) {ans=i;};
Variable ans
is local and not null, yet segmentation fault occurs.
Why is that and how can I fix it?
#include <stdio.h>
int* finder(int *begin, int *end, int item)
{
int *ans=0; int *i=begin;
while (i<end) {
if (*i==item) {ans=i;};
i++;
}
return ans;
}
int main()
{
int arSize, target, i=0;
int arr[10]={};
int *first=&arr[0]; int *last; int *result;
printf("Find element: ");
scanf("&d",&target);
printf("Array size: ");
scanf("&d",&arSize);
printf("Enter array: ");
while (i<arSize){
scanf("&d",&arr[i]);
i++;
}
last=&arr[arSize];
result=finder(first,last,target);
printf("%s %p","Target's address is ",result);
return 0;
}