This algorithm is a linear search algorithm that finds the desired value. But when I compile this code, gives the segmentation fault in if(dizi[i]==aranan) this line. How can I solve this ?
#include <stdio.h>
int N,i,aranan;
int ArrayBastir(int *dizi,int N)
{
printf("My numbers\n");
for(int i =0; i<N;i++)
{
printf("%d\n", dizi[i]);
}
}
int findValue()
{
printf("The value you want to search");
scanf("%d",&aranan);
}
int Output(int *dizi,int N,int aranan)
{
for(int i =0; i<N;i++)
{
if(dizi[i]==aranan)
{
printf("%d number %d. found in queue \n", aranan,i+1);
}
}
}
int main() {
int N;
int aranan;
printf("Please enter how many numbers you want to enter");
scanf("%d", &N);
int dizi[N];
for(int i =0; i<N;i++)
{
scanf("%d", &dizi[i]);
}
ArrayBastir( dizi, N);
findValue(aranan);
Output(*dizi,N,aranan);
return 1;
}
Linear Search algorithm
You have two objects defined as:
Once is defined at file scope (a global), and one is defined within the scope of
main.When
findValue(aranan)is called, a copy of the uninitialized value ofarananwithin the scope ofmainis passed tofindValue.findValueis lacking a prototype, having not declared its arguments, so this is ignored.findValuescans a value into the file scopearanan, but whenOutput(*dizi, N, aranan)is called it uses the value ofaranandefined withinmain.arananwithinmainwas never initialized, and thus this causesOutputto search for an indeterminate value.Additionally,
*diziis anint, whenOutputexpects anint *as its first argument.ArrayBastirandOutputare also defined as each returning anint, which they do not do.You should not ignore the return value of
scanf, as it indicates the number of successful conversions, or a negative value on failure (EOF). In a program this small, you can get away with writing a simple wrapper function for reading integers, that just exits the program if the user enters something invalid.mainreturning nonzero generally indicates your program failed.mainis special - it is the only non-void function where you can omit a return statement. Ifmainreaches the end of execution without an explicitreturn, it is treated as though it returned0.The issues above can be mitigated by avoiding the use of global variables, and by turning up your compilers warning level to catch obvious type mismatches.
For GCC or Clang, use
-Wall -Wextra, and possibly-Werror.For MSVC, use
/Wall, and possibly/Wx.Minimally refactored: