Reputation: 53
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;
}
Upvotes: 2
Views: 82
Reputation: 2015
Probably it fails on the last iteration inside finder() in case the arSize is equal 10.
You declared an array 'arr[10]', so it means that the index of the last element is equal 9, not 10 :)
So, you should change one line in main():
last=&arr[arSize];
to:
last=&arr[arSize-1];
Of course, you should always check that arSize is <= 10.
Upvotes: 0
Reputation: 14493
The scanf()
format have typo: they use '&'
instead of '%
. As a result, the program (as posted) does not read any input.
Suggestion: make sure you get CLEAN compile (no warning, no errors) before trying to run (or debug). GCC flagged the format errors with the default 'cc'.
ff.c:22:11: warning: too many arguments for format [-Wformat-extra-args]
scanf("&d",&target); ^~~~
3 fixes are needed.
scanf("&d",&target);
scanf("&d",&arSize);
scanf("&d",&arr[i]);
For example:
printf("Array size: ");
// BAD: scanf("&d",&arSize);
scanf("%d",&arSize);
Code seems to run fine on simple cases with this fix.
Upvotes: 4