I was given the assignment of writing a C code which contains a function, which when passed through an array of length n returns a pointer to the array’s largest element. In order to make it easy for us, the length n was set to 10.
I wrote the code below and compiled it and it didn't show any error. Then, I ran this code and it asked for the 10 inputs for the array, but instead of returning the pointer with the largest element, it read segmentation fault 11.
I am new to pointers, and so could not figure out what exactly went wrong. Any help will be greatly appreciated.
#include<stdio.h>
#define N 10
int *find_largest(int a[], int n)
{
int i;
int *max;
*max = a[0];
for(i = 1; i < n; i++)
{
if(a[i] > *max)
*max = a[i];
}
return max;
// this function returns the pointer with the max. value
}
int main(void)
{
int b[N], i;
int *p;
printf("Enter %d numbers: ", N);
for(i = 0; i < N; i++)
scanf("%d", &b[i]);
//scans all the inputs
p = find_largest(b, N);
//p gets assigned the value of the max valued pointer
printf("largest element: %d", *p);
return 0;
}
Edit- After looking at the wonderful advices given, I modified my code a bit. I changed *max=a[0]
to max= &a[0]
, and *max=a[i]
to max=&a[i]
. Now, the code runs without any error, but instead of returning the pointer with the largest value, it returns the largest input instead.