简体   繁体   中英

C function to find largest element in an array of integers

Consider the C function

int largest(int list[], int n, int l);
  • list is a list of n integers.
  • l is temp space for the function

The function is supposed to return the largest integer in the list of n integers in the array list .

int largest(int list[], int n, int l) {
   int i;
   for(i=0; i<n; i++) {
      if(list[i] > l) {
         l = list[i];
      }
   }
   return l;
}

Why is this function returning bad data at times?

Looks to me like you are trying to print the value l but you are not actually storing the return value of the function. Also you don't need to pass l as a parameter to your function.

Do this instead:

   // Declare the function prototype without int l.
   int largest(int list[], int n);

   // Actual function that searches for largest int.
   int largest(int list[], int n) 
   {
      int i;
      int l = list[0]; // Point to first element. 

      // Notice loop starts at i = 1.
      for(i = 1; i < n; i++) 
      {
         if(list[i] > l) 
           l = list[i]; 
      }

      return l;
   }

Then where you call your function do this:

int l = largest(list, n);

This code above just ensures that you store the value that your function returns.

You never initialize l , so it will return the existing value of this if none of the items in the list were larger than it. If you never initialized it in the calling function then the behaviour is undefined, which would explain your "bad data".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM