Hi,
I'm having some problems with a function. The function is supposed to find the two largest values in an array.
Code:
void find_two_largest( const int *a, int n, int *largest, int *second_largest){
largest = a;
int temp;
second_largest = a;
for ( int i = 1; i < n; i++){
if (*(a + i) > *largest){
temp = *largest;
*largest = *(a + i);
*second_largest = temp;
}
else if (*(a+i) > *second_largest)
*second_largest = *(a+i);
}
}
I don't see any mistake with the code of the function, but when I try to call it inside my program it only returns 0 for both largest and second_largest.
Code:
int *find_middle( int *a, int n);
void find_two_largest(const int *a, int n, int *largest, int *second_largest);
int main()
{
int n;
printf("No. of elements?");
scanf("%d",&n);
int a[n];
printf("Elements of array:");
for (int i=0; i<n; i++)
scanf("%d", &a[i]);
int largest, second_largest;
find_two_largest(a, n, &largest, &second_largest);
printf("Largest element is %d, second largest is %d", largest, second_largest);
}
Can someone tell me what I'm doing wrong. Do I have to declare the variables largest and second_largest as normal integer variables and then pass their addresses as arguments to find_largest or is that incorrect?