2

I try to find the maximum and the minimum of an array using pointers but after I enter the values and display them, my program crashes and I don't know why.Where's my mistake? This is my code.The program is working if remove the minimmaxim function.

I just start to learn dynamic allocation and pointers.

#include <stdio.h>
#include <stdlib.h>
// function to enter the real values of an array
void pcitireVector(double *a, unsigned int n)
{
    int i;
    for(i=0;i<n;++i)
    {
        printf("a(%d)", i);
        scanf("%lf", &a[i]);
    }
}
// function to display the array
void pafisareVector(double *a, unsigned int n)
{
    int i;
    for(i=0;i<n;++i)
    {
        printf("%lf",a[i]);
        printf(" ");
    }
}
// function which displays the minimum and the maximum of the array using pointers.
void minimmaxim(double *a, unsigned int n)
{
    int i;
    double *min=0, *max=0;
    *min=a[0];
    *max=a[0];
    for(i=0;i<n;++i)
    {
        if(a[i]>*max)
        {
            *max=a[i];
        }
        else
        {
            if(a[i]<*min)
            {
                *min=a[i];
            }
        }
    }
    printf("minimul este %lf", *min);
    printf("maximul este %lf", *max);
}
int main(void)
{
    int n;
    double *x;
    printf("Baga-l pe n"); // enter the size of the array
    scanf("%d", &n);
    x=(double *)malloc(n*sizeof(double));
    if(x==0)
    {
        printf("eroare la alocarea memoriei"); // error
        exit(EXIT_FAILURE);
    }
    pcitireVector(x,n);
    pafisareVector(x,n);
    minimmaxim(x,n);
    return 0;
}

1 Answer 1

1

It crashed here:

double *min=0, *max=0;

You declared pointers but haven't pointed them to anywhere yet. So where those min and max pointers are pointing to are undefined, they are pointing to some random addresses.. You then tried to jump into those random addresses and set the value there which lead to crashes.

In fact, you don't need min, max to be pointers at all, they can just be local variables. Do this, and you'll be ok:

double min, max;
min=a[0];
max=a[0];

for(i=0;i<n;++i)
{
    if(a[i]>max)
    {
        max=a[i];
    }
    else
    {
        if(a[i]<min)
        {
            min=a[i];
        }
    }
}

printf("min = %lf", min);
printf("max = %lf", max);
Sign up to request clarification or add additional context in comments.

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.