Fethi Tekyaygil Fethi Tekyaygil - 3 months ago 13
C Question

C Searching A Value In Manually Filled Array

I'm trying to write a program which includes an array that filled by user and find a value in it which specified by user then print if it found and count of that number in array.But it works only for first element of array.My code is below:

`void searchh(int arr[],int search,int number,int counter);

int main()
{
int number,search,i;
int counter=0;


printf("How many numbers will you enter?");
scanf("%d",&number);

int array[number];

for(i=0;i<number;i++){
printf("Please enter the %d. element of the array:",i+1);
scanf("%d",&array[i]);
}


printf("Please enter the number that you're looking for:");
scanf("%d",&search);

searchh(array,search,number,counter);


return 0;
}

void searchh(int arr[],int search,int number,int counter){
int i,c;
int key=search;
int num=number;
counter=0;

int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];


for(i=0;i<arrsize;i++)
{

if(arr[i]==key)
{
arrayent[counter]=i;
counter++;
}
}

printf("The number that you're looking for which is %d is found %d times.\nLocations:",key,counter);

if(counter>0){
for(c=0;c<sizeof(arrayent)/sizeof(int);c++){
printf("%d\n",arrayent[c]);
}
}

else
printf("Number doesn't exist!!");


}`


And Outputs:

Output That Works
Output That Doesn't Work

Thanks for your helps.

Answer
int arrsize=(int)(sizeof(arr)/sizeof(int));

This already doesn't do what you think it does. sizeof(arr) - could be 4 if size of pointer is 4 bytes. In other words you can't check array size like that inside function, arr decays to pointer of first element of array. Hence sizeof(arr) will return size of pointer which could be 4 or 8. You need to pass the number of elements of the array to the function as parameter - which is number in your case.

This:

int arrayent[(int)(sizeof(num)/sizeof(int))];

is also strange. num is int. sizeof(num) and sizeof(int) will be same - and division will give you 1.


IMO these two lines

int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];

should just go as

int arrsize = number;
int arrayent[number];

PS. Also try to use a debugger to help you with some kind of issues.