Reputation: 15
I know many solutions exist for this one, but after looking around I haven't found any that involves pointers
Right now it keep throwing warnings and there's no output at all, what am I doing wrong?
#include <stdio.h>
int findbig (int a[], int n)
{
int max = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > max)
{
max = a[i];
}
}
return max;
}
int main (void)
{
int n;
printf("How many numbers? \n");
scanf("%d", &n);
int a[n];
printf("Now enter those %d numbers: \n", n);
for (int i = 1; i < n; i++)
{
scanf("%d", &a[i]);
}
int biggest = findbig (a[n], n);
printf("The biggest number is: %d\n", biggest);
return 0;
}
My compiler is complaining that:
-warning: passing argument 1 of 'findbig' makes pointer from integer without a cast [enabled by default]
-note: expected 'int *' but argument is of type 'int'
Upvotes: 0
Views: 81
Reputation: 499
This line is wrong.
int a[n]
Array should be initialized with constant value, because the space of array is allocated before execution of the program. So, variables won't work.
Upvotes: -2
Reputation: 124632
a[n]
(as well as its equivalent *(a + n)
form) is an int, not a pointer to int. It's also one past the boundary of your array. You need to turn your warnings into errors. You pass an int, whose value is converted to a pointer (address), which is, well, no good.
You need to call your function like so:
findbig(a, n);
Regardless of your signature, findbig
receives a pointer to int. You cannot pass arrays to (or return them from) functions in C. They degrade to pointers to their first element.
On a side note, you're always skipping the first element when populating the array, so the user says "I want to enter N numbers", but you only allow them to enter n-1
. The is also problematic as you use a[0]
as your initial max
number, but the value of that element is indeterminate.
It could be anything, i.e., some huge number, and then your function will give strange results. Either initialize the array to 0 (int a[n] = {0};
) or start your loop at 0 (better).
Upvotes: 3
Reputation: 6005
By indexing a
, doing a[n]
, you get the value of the array a in the n-th index, which is of int type
. You need to invoke findbig(....);
function using the array "pointer" variable, without indexing it, by doing:
findbig(a, n);
Upvotes: 0