I’m getting a compile errors, that I can’t really fix. I need to create a program that initializes an in array, then write a biggest function that takes 2 parameters, an array and it’s length and returns the index of the largest element in the array. I will then call this function from main. Can anyone tell me what is the problem?
errors:part1.c: part1.c: In function 'main':
part1.c:6:3: warning: implicit declaration of function 'largest'
part1.c:7:23: error: expected expression before ']' token
part1.c: In function 'largest':
part1.c:17:4: warning: statement with no effect
Thanks!
#include <stdio.h>
int main()
{
int myArray[]={1,2,3,4,5,6};
largest(myArray,6);
printf("%d",myArray[]);
return 0;
}
int largest(int array[], int length)
{
length = sizeof(array)/sizeof(array[0]);
int i = 1;
int max = array[0];
for(i; i<length; i++)
{
if(max < array[i])
{
max = array[i];
}
}
return max;
}
C compiles your code in one pass. This means that everything should be defined before it is used. Your function
largestis defined after its use, therefore once the compiler seesit still doesn’t know that
largestexists!The solution would be to either move the definition of
largestabovemain, or better, forward declare the function:Also, the
sizeof(array)will not give you the number of elements inlargestbecause that information is lost upon function call. You could move that expression up in the function call to compute and pass the length parameter:This may also be a typo, but you probably meant to store and print the maximum value: