Let's start from the very beginning.
The header <conio.h>
is not a standard header and neither declaration from the header is used in the program. So this directive
#include<conio.h>
may be removed.
The function search
is declared with three parameters of the type int
int search(int ,int ,int );
That is it does not accept an array.
And the return type of the function is again int
instead of a pointer type.
Pay attention to that the function will not change a passed array. So the function declaration will look like
int * search( const int[] ,size_t , int );
The second parameter that specifies the number of elements in the passed array has the unsigned integer type size_t
instead of the signed integer type int
. That is the number of elements in an array can not be a negative value. So there is no sense to declare this parameter as having a signed integer type.
Also your function returns nothing if the target element is not found in the array.
In this declaration
int i,a[i],target,*p,n;
you declared a variable length array a[i]
. But the variable i
has not initialized yet. So this declaration is invalid and results in undefined behavior.
And moreover the number of elements in the array is stored in the variable n
:
pritnf("enter number of numbers u want");
scanf("%d",&n);
So you need to declare the array after the variable n
will get its value.
In this call of printf
printf("target found at %d",p);
there is used invalid conversion specifier %d
with a pointer. This invokes undefined behavior.
You need to use at least the conversion specifier %p
instead of %d
.
And at last the function main
shall have the return type int
.
int main( void )
The program can look the following way.
#include <stdio.h>
int * search( const int[], size_t, int );
int main( void )
{
size_t n = 0;
pritnf( "enter number of numbers u want: " );
if ( scanf( "%zu", &n ) == 1 && n != 0 )
{
int a[n];
int target = 0;
int *p = NULL;
printf( "enter numbers you want in array\n" );
for ( size_t i = 0; i < n; i++ )
{
scanf( "%d", a + i );
}
printf( "enter the number u are searching: " );
scanf( "%d", &target );
p = search( a, n, target );
if ( p == NULL )
{
printf( "target not found\n" );
}
else
{
printf( "target found at %p\n", ( void * )p );
}
}
}
int * search( const int a[], size_t n, int target )
{
const int *p = NULL;
if ( n != 0 )
{
p = a;
while ( p != a + n && *p != target ) ++p;
if ( p == a + n ) p = NULL;
}
return ( int * )p;
}