Hello, I have a problem with this search.I know what the algoritm must do, but when I enter a number above 10 it says the number is in the array but that is not in the array and I don't know how to make it work.
#include <iostream>
using namespace std;
int linear_search(int *a,int n,int x)
{
int i;
for(i = 0; i < n; ++i){
if(x == *(a+i)
{
return i;
}
}
return -1;
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
int x,i;
int n = sizeof(a);
cout << "Enter the number that must be searched:" << endl;
cin >> x;
int result = linear_search(a,n,x);
if(result >= 0)
{
std::cout<<"The number "<<a[result]<<"======was found @ =====" <<result<< " index "<<endl;
}
else{cout << "Number not found in array!!! " << endl;}
The problem is this: int n = sizeof(a);
This sets n to the number of bytes in array a, not the number of entries in the array. Since each int typically takes 4 bytes, this is probably setting n to 40 instead of 10. That means causes linear_search() to look for array entries that don't exist and when that happens, you get undefined behavior, which means anything can happen.
The recommended way to fix this is to use std::array instead of raw arrays. But if you want to use arrays, try this: int n = sizeof(a) / sizeof(a[0]);
This divides the total size of the array by the size of the first element, resulting in the number of elements in the array.
#include <iostream>
usingnamespace std;
int linear_search(int *a,int n,int x)
{
int i;
for(i = 0; i < n; ++i)
{
if(x == *(a+i) // syntax error for sure
// try: if(x == *(a+i))
{
return i;
}
}
return -1;
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
int x,i;
int n = sizeof(a); // n != 10, n == 10 * sizeof int
// try int n = sizeof(a) / sizeof(a[0]);
cout << "Enter the number that must be searched:" << endl;
cin >> x;
int result = linear_search(a,n,x);
if(result >= 0)
{
std::cout<<"The number "<<a[result]<<"======was found @ =====" <<result<< " index "<<endl;
}
else
{
cout << "Number not found in array!!! " << endl;
}
return 0;
}