| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Im just learning how to use arrays in c and for this particular assignment I am supposed to use a linear search using recursion and i keep getting a segmentation fault:
#define SIZE 100 int linearSearch( const int array[], int key,int size); int main() {int a[SIZE], x, searchKey, element; for(x=0; x<SIZE; x++){a[x]=2*x;} printf("enter integer search key:\n"); scanf("%d", &searchKey); element = linearSearch(a,searchKey,SIZE); if (element!= -1) printf("found value in element %d\n", element); else printf("value not found\n"); } int linearSearch(const int array[], int key,int size) {int n; if(n<size && array[n]==key) return n; return -1; } The program allows the user to put in a search key and then gives a segmentation fault |
|
#2
|
|||
|
|||
|
First off, put your code inside a code tag (the # sign) to make it more readable.
Second off, n inside of linearSearch is not initialzed. You'll get whatever happens to be on the stack at the time of the call to linearSearch, ie. garbage - you need to initialize this before using it. Third off, linearSearch is not recursive. To be recursive it must call itself, either directly or inderectly. You need to figure recursion out on your own or you wont understand it. I struggled with it for a long, long time before it made sense and then it just kinda clicked. Look at some examples in your book, and rememer that you need to know what condition is going to end the recursion and make sure you check for it! Why recursively? This must be a class and you have to do this recursively, right? It would be a whole lot simpler to do iteratively. Code:
int linearSearch(const int array[], int key,int size)
{
static int n = 0;
if (n<size && array[n]==key)
{
return n;
}
else if (n < size)
{
++n;
linearSearch(array, key, size);
}
else
{
return -1;
}
}
Should get you in the ballpark, though I haven't coded it to see if it works or not! Also, this is only one solution. There are other ways to approach this. Dang it, now you wont learn recursion on your own. PS This will only work once, as n will not get reset to 0. |
|
#3
|
|||
|
|||
|
Use this linearSearch function and your program will work.
int linearSearch(const int array[], int key,int size) {int n=0; for(n=0;n<size;n++) { if(array[n] == key) return n; } return -1; } ~ |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > segmentation fault c |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|