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;
}