Thread: Find Largest Number in File [array]

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    7

    Find Largest Number in File [array]

    I have a following code, where I tried to find out largest number from .txt file.
    In void function "maks" I successfully load numbers in array, variable "broj" is used to determine how many numbers from file to read, from which I look for a largest number. I'm constantly getting SIGSEGV fault, I'm not sure what's the problem.
    Input should be like:
    ./program1 list.txt 5 max (where list.txt is name of a file, 5 is number of numbers to be read from file, max to find largest number)
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void maks(int broj, FILE *file)
    { 
      int i = 0, polje[i], max;
      for(i = 0; i<=broj; i++)
        fscanf(file, "%d", &polje[i]);
      
      max = polje[0];
    
      for (i = 0; i<= broj; i++){
     // printf("%d\t", polje[i]);
        if(polje[i] > max){
          max = polje[i];
        }  
      }
      printf("Najveci broj:\n%d\n", max);
    
    }
    int main(int argc, char *argv[])
    { 
      if(argc != 4){
        fprintf(stderr, "Greska na ulazu.\n");
        return 0;
      }
      char *buf = argv[2]; 
      int broj = atoi(buf);
      
      FILE *file;
      file = fopen(argv[1], "r");
      if(strcmp(argv[3], "max") == 0)
        maks(broj, file);
      
    return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    First do you realize that you could do this without the array?

    Second do you realize that you're using the variable i before it is assigned an actual valid value? It has the value of zero when you're trying to define the polje array.

    Third to you even realize that you're trying to use a VLA (Variable Length Array)?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Find smallest and largest Number of Array.
    By Kexplx in forum C Programming
    Replies: 1
    Last Post: 11-02-2015, 05:47 PM
  2. Replies: 3
    Last Post: 01-30-2013, 09:30 AM
  3. Find the Largest and Smallest Number
    By Nightsky in forum C Programming
    Replies: 27
    Last Post: 09-04-2006, 03:40 PM
  4. Find largest and second largest number (help)
    By Arkon in forum C++ Programming
    Replies: 6
    Last Post: 01-20-2006, 11:21 PM
  5. how do u find 2nd largest number??
    By juancardenas in forum C Programming
    Replies: 8
    Last Post: 02-14-2003, 08:28 AM

Tags for this Thread