【发布时间】:2020-04-01 12:12:51
【问题描述】:
我尝试使用指针找到数组的最大值和最小值,但是在输入值并显示它们之后,我的程序崩溃了,我不知道为什么。我的错误在哪里? 这是我的代码。如果删除 minimmaxim 函数,程序就可以工作。
我刚开始学习动态分配和指针。
#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;
}
【问题讨论】:
标签: c arrays function dynamic-memory-allocation