简体   繁体   中英

I'm trying to return two largest numbers in an array and I'm getting segmentation fault

#include <stdio.h>

int main ()
{
  int n, i;
  int arr[n];
  int max1 = 0;
  int max2 = 0;

  // introducing array elements 
  printf ("Enter n: ");
  scanf ("%d", &n);
  for (i = 0; i < n; i++)
    {
      scanf ("%d", &arr[i]);
    }
    
  // calculating max1, largest number


  for (i = 0; i < n; i++)
    {
      if (arr[i] >= max1)
    max1 = arr[i];
    }

  printf ("The first maximum is %d\n", max1);


  // calculating max2, iterate the array again


  for (i = 0; i < n; i++)
    {
      if ((arr[i] >= max2) && (arr[i] != max1))
            max2 = arr[i];
    }

  printf ("The second max is %d", max2);
}

The problem asks me to read an one dimension array and find the two largest numbers in this array. I tried to solve it in a less efficient way, so I will first iterate the entire array in order to find the first maximum, then iterate it again to find the second one. My error is segmentation fault (Core dumped) and I don't understand where I did wrong.

You're not allowed to set a stack allocated array using a variable at:

int arr[n];

You are allowed to do this:

int arr[10] //or any number

Basically the size of the array has to be known at compile time. You've also never set actually set n to a number.

Edit: This apparently incorrect in modern c you are allowed to do this.

It should be like this

#include <stdio.h>

int main ()
{
  int n, i;
  
  int max1 = 0;
  int max2 = 0;
  
  printf ("Enter n: ");
  scanf ("%d", &n);
  int arr[n];

  // introducing array elements 
  
  for (i = 0; i < n; i++)
    {
      scanf ("%d", &arr[i]);
    }
    
  // calculating max1, largest number


  for (i = 0; i < n; i++)
    {
      if (arr[i] >= max1)
    max1 = arr[i];
    }

  printf ("The first maximum is %d\n", max1);


  // calculating max2, iterate the array again


  for (i = 0; i < n; i++)
    {
      if ((arr[i] >= max2) && (arr[i] != max1))
            max2 = arr[i];
    }

  printf ("The second max is %d", max2);
}

note this

printf ("Enter n: ");
scanf ("%d", &n);
int arr[n];

your compiler gives an arbitrary garbage value to n, in your code and that possibly is smaller than the number of iterations you have.

I,however, doubt the working of my code in some classic compilers as they want you to put all the declarations on the top

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