-3

im new to this and trying to write a code to find the maximum and minimum between 2 numbers with a header file. im pretty sure im doing it wrong so if anyone could help guide me that'd be so helpful

#include <stdio.h>
#include <maxmin.h>
int main()
{

    //declare variables
    float maximum;
    float minimum;
    float n1;
    float n2;

    //get numbers
    printf("Enter two numbers:");
    scanf("%f%f",&n1,n2);

    //call functions
    maximum= max(n1, n2);
    minimum= min(n1, n2);

    //print results
    printf("maximum= %f\n", max);
    printf("minimum= %f\n", min);
    return 0;
}

and hereʻs the header file:

// function to find max
float max(float n1, float n2)
{
    return(n1>n2) ? n1 : n2;
}

//function to find min
float min(float n1, float n2)
{
    return(n1 > n2) ? n2 : n1;
}
  • 4
    Now is the time to learn how to use a debugger to find out where it segfaults. And you should check the return values for scanf. – klutt Oct 10 '19 at 23:42
  • Please do read [this](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – gustgr Oct 10 '19 at 23:45
  • 1
    Don't define functions in a header file unless they are `static`, so you don't get duplicate definitions if you include them in more than one file. Usually, functions defined in header files are `inline`. – Kaz Oct 10 '19 at 23:50
  • Possible duplicate of [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – Badda Oct 11 '19 at 00:32

1 Answers1

1

A segmentation fault is caused when you try to access illegal memory. Some common causes of this are trying to access an index of an array which does not exist (e.g. trying to access the third element in an array that only has two elements) or trying to access a variable that has not been initialized. See this answer for a more detailed explanation.

In your case, you are trying to access variables that are not initialized.

These lines...

printf("Enter two numbers:");
scanf("%f%f",&n1,n2);

to this...

printf("Enter two numbers:");
scanf("%f%f",&n1,&n2);

You are missing an & in front of one of n2.

And change these lines...

printf("maximum= %f\n", max);
printf("minimum= %f\n", min);

to be this...

printf("maximum= %f\n", maximum);
printf("minimum= %f\n", minimum);

In your code, max and min are functions defined in maxmin.h while maximum and minimum are the variables that you initialize and write to when you are computing the maximum and minimum values.