c - Function to return a pointer to the largest number in an array -
as can tell title need write function returns pointer largest number in array, functions gets pointer double array , it's size. in addition need write main function use function. here code wrote:
#include <stdio.h> #include <stdlib.h> void bigel(double* arr, double arrsize); void bigel(double* arr, double arrsize) { int i; double maximum, *x; maximum = arr[0]; (i = 1; < arrsize; i++) { if (arr[i]>maximum) { maximum = arr[i]; } } *x = maximum; } void main() { double myarr[10]; int i; printf("please insert 10 numbers array\n"); (i = 0; < 10; i++) { scanf("%d", &myarr[i]); } bigel(myarr, 10); }
i error:
error 1 error c4700: uninitialized local variable 'x' used
i don't understand did wrong because did initialized x. kind of appreciated, in addition, tell me if idea of code right because im not sure if understood question correctly.
you did not initialize variable x
. merely wrote the location pointed x
, here:
*x = maximum;
when x
uninitialized, compiler complaining about.
you want like:
double * bigel(double* arr, size_t arrsize) { size_t i; double *max = arr; (i = 1; < arrsize; i++) if (arr[i] > *max) max = &arr[i]; return max; }
things i've changed:
- use
size_t
array size , counter, notdouble
,int
. - retain pointer maximum element, not maximum element's value.
- return pointer maximum element.
- remove superflous braces.
Comments
Post a Comment