Thread: Highest Number in Array Problem (Beginner)

  1. #1
    Registered User
    Join Date
    Jan 2019
    Posts
    15

    Highest Number in Array Problem (Beginner)

    Hello Again!

    On this Super Bowl Sunday, I am working through some problems in my C book. This post is about writing a function that returns the largest element in an array.

    When running my program, I get memory issues at greater array lengths. For example, choose array length of "5" and the elements of the array as "1 100 3 4 5": the output is correct, namely that the largest element is "100", but then the program also crashes with "error: memory read failed for 0x7fff000000002."

    I'd like to know two things: 1) What is wrong with my code? and 2) What does this memory failure mean?

    Code pasted below. Thank you all for your help!

    Code:
    #include <stdio.h>
    
    
    int largest_element(int n, int a[n]);
    
    
    int main(){
        
        int b[] = {0}, i, z;
        
        printf("Enter the length of the array: ");
        scanf("%d", &z);
        
        printf("Enter the values of the array: ");
        
        for (i = 0; i < z; i++){
            scanf("%d", &b[i]);
        }
        
        largest_element(z, b);
        
        return 0;
    }
    
    
    int largest_element(int n, int a[n]){
        
        int hi = 0, i;
        
        for (i = 0; i < n; i++){
            if (a[i] > hi){
                hi = a[i];
            }
        }
        
        return printf("The largest element is %d\n", hi);
        
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    26,319
    You need to specify the size of the array. By leaving that empty you're saying to deduce the size from the number of elements in the initialiser, i.e., you only have an array of 1 element, so you cannot store more than that.

    So, #define the size, then use it in the array declaration as well as to force the user to enter a length of the array that does not exceed this size.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2019
    Posts
    15
    Thanks! I just would like to clarify something about variable-length arrays. I thought that the length of an array can be defined by my first function parameter "n," and once the user inputs "n" that will then specify the second parameter, namely the length of the array.

    From your answer, I gather you are saying that I cannot have the user input the size of the array; instead, I have to define the size of the array in the code. Is that right?

    Quote Originally Posted by laserlight View Post
    You need to specify the size of the array. By leaving that empty you're saying to deduce the size from the number of elements in the initialiser, i.e., you only have an array of 1 element, so you cannot store more than that.

    So, #define the size, then use it in the array declaration as well as to force the user to enter a length of the array that does not exceed this size.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    26,319
    No, you can ask the user to input the length of the array, but your array must be large enough for that length. This can be done in one of three ways:
    • Declare a fixed size array large enough to accommodate whatever the valid range of user input for the array length, then only use the elements up to the length input. This is what I'm suggesting.
    • Dynamically allocate an array of the length input by the user.
    • Create a variable length array of the length input by the user. This means you have to declare the array after reading input by the user. However, although the variable length array feature is standard, it is an optional part of the standard, so I don't recommend it unless you are explicitly targeting a compiler that supports it.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Jan 2019
    Posts
    15
    I understand better now, and appreciate the practical advice. From here on, I will follow your first recommendation.

    Nonetheless, to understand VLA a bit more, could you provide an example using part of my code? If not mine, happy to learn from another example. Thanks!

    The relevant code is as follows:

    Code:
    #include <stdio.h>
    
    
    #define LEN 100
    
    
    int largest_element(int n, int a[n]);
    
    
    int main(){
        
        int i, z, b[LEN]={0};
        
        printf("Enter the length of the array: ");
        scanf("%d", &z);
        
        printf("Enter the values of the array: ");
        
        for (i = 0; i < z; i++){
            scanf("%d", &b[i]);
        }
        
        largest_element(z, b);
        
        return 0;
    }
    
    
    
    
    int largest_element(int n, int a[n]){
        
        int hi = 0, i;
        
        for (i = 0; i < n; i++){
            if (a[i] > hi){
                hi = a[i];
            }
        }
        
        return printf("The largest element is %d\n", hi);
        
    }
    Quote Originally Posted by laserlight View Post
    No, you can ask the user to input the length of the array, but your array must be large enough for that length. This can be done in one of three ways:
    • Declare a fixed size array large enough to accommodate whatever the valid range of user input for the array length, then only use the elements up to the length input. This is what I'm suggesting.
    • Dynamically allocate an array of the length input by the user.
    • Create a variable length array of the length input by the user. This means you have to declare the array after reading input by the user. However, although the variable length array feature is standard, it is an optional part of the standard, so I don't recommend it unless you are explicitly targeting a compiler that supports it.
    Last edited by SanFi; 2 Weeks Ago at 12:49 PM. Reason: Didn't paste full code

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    26,319
    This would be a rewrite of your code to use variable length arrays properly:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int find_largest_element(const int elements[], size_t n);
    
    int main(void) {
        size_t num_values;
        printf("Enter the length of the array: ");
        if (!(scanf("%zu", &num_values) == 1 && num_values > 0)) {
            fprintf(stderr, "Error: the length of the array must be a positive integer.\n");
            return EXIT_FAILURE;
        }
    
        int values[num_values];
        printf("Enter the values of the array: ");
        for (size_t i = 0; i < num_values; i++) {
            if (scanf("%d", &values[i]) != 1) {
                fprintf(stderr, "Error: could not read value #%zu as an integer.\n", i + 1);
                return EXIT_FAILURE;
            }
        }
    
        printf("The largest element is %d\n", find_largest_element(values, num_values));
    
        return 0;
    }
    
    int find_largest_element(const int elements[], size_t n) {
        int largest_element = 0;
    
        for (size_t i = 0; i < n; i++) {
            if (elements[i] > largest_element) {
                largest_element = elements[i];
            }
        }
    
        return largest_element;
    }
    Observe that:
    • I renamed largest_element to find_largest_element since that is what the function does.
    • Instead of printing the largest element, find_largest_element returns it. This means that you can easily reuse the function say, if you want a different text to use when printing the largest element, or if you want to do something with the largest element other than print it. Another reusable approach is to return the index of or a pointer to the largest element.
    • I used size_t rather than int for the size/length of the array. Note that this means you have to compile with respect to C99 or later in order for the %zu format specifier to work, but since a variable length array (standardised in C99) will be used that is a given.
    • I checked the return value of scanf, and printed appropriate error messages.
    • I swapped the order of parameters for the helper function as it is more typical to pass the array and then the number of elements of the array.

    I also left in place a bug with find_largest_element that you can discover if you test by entering only negative integers as the values.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Jan 2019
    Posts
    15
    Thanks so much Laserlight! I've been applying your code to some of my work, and it works really well.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lowest and highest number in loop
    By Anders Ekdahl in forum C Programming
    Replies: 5
    Last Post: 10-14-2015, 11:03 AM
  2. Beginner. Help with displaying highest and lowest numbers
    By SkywardTaco in forum C++ Programming
    Replies: 9
    Last Post: 04-27-2015, 12:34 PM
  3. Finding Highest Number in Array
    By nlp412 in forum C++ Programming
    Replies: 1
    Last Post: 08-12-2014, 09:14 PM
  4. HELP: Exclude the highest and lowest number...
    By Ocin101 in forum C Programming
    Replies: 12
    Last Post: 07-21-2009, 01:51 AM
  5. finding highest number entered
    By volk in forum C++ Programming
    Replies: 11
    Last Post: 03-23-2003, 01:22 AM

Tags for this Thread