0

I would like to write a program which finds the minimal number of 5 inputted numbers. I'm stuck at the point when I want to use function getMinNum, but there is an error saying: expected expression before ']' token I understand it has a connection with pointers, however I would like to do it without them if it is possible of course.

#include <stdio.h>
#include <stdlib.h>

float getMinNum(float a[], int x);
int main() 
{
    int n = 5;
    int i;
    float z[n];
    for(i=0; i<n; i++){
        scanf("%f", &z[i]);
    }

    printf("%6.2f", getMinNum(z[], n));
    return 0;
}

float getMinNum(float a[], int x)
{
    int i, min = a[0];
    for(i=0; i<x; i++){
        if(min > a[i+1]){
            min = a[i+1];
        }
    }
    return min;
}
2
  • 2
    Note that you can start the loop in getMinNum() with i = 1; you know that a[0] is the same value as what's in min...well, if min was a float and not an int, you would. You should check that the fscanf() calls all succeed before using the data. You're also using a VLA (variable length array). No harm done, but you should be aware that you're doing so. Commented Nov 8, 2017 at 4:22
  • Specifically, you should be aware that you're using a variable length array because the compiler may allow you to set n = 0. This would lead to out-of-range memory access using @ed-heal's solution, which assumes a[0] is a valid member. If you declare z with float z[5], the compiler will enforce that assumption. Commented Nov 8, 2017 at 6:28

2 Answers 2

3

You shouldn't append '[]' to the variable name.

Instead of:

printf("%6.2f", getMinNum(z[], n));

do:

printf("%6.2f", getMinNum(z, n));
Sign up to request clarification or add additional context in comments.

Comments

3

Your a[i+1] will be using values outside the array, so use a[i] instead.

So the code should look like

float getMinNum(float a[], int x){

    int i;
    float min = a[0]; // Min needs to be a float
    for(i=1; i<x; i++){ // Do not need to check a[0]

        if(min > a[i]){
            min = a[i];
        }

    }

    return min;
}

And call it as

printf("%6.2f", getMinNum(z, n));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.