【问题标题】:maximum and minimum of an array using pointers in C使用C中的指针的数组的最大值和最小值
【发布时间】: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


    【解决方案1】:

    这里崩溃了:

    double *min=0, *max=0;
    

    您声明了指针,但尚未将它们指向任何地方。因此,那些minmax 指针指向的地方是未定义的,它们指向一些随机地址。然后您尝试跳转到这些随机地址并在那里设置导致崩溃的值。

    事实上,你根本不需要 min, max 是指针,它们可以只是局部变量。这样做,你会没事的:

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

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 2017-02-13
      • 2019-05-07
      • 1970-01-01
      • 2016-10-06
      • 2013-10-28
      • 1970-01-01
      • 2011-03-27
      • 2017-06-26
      相关资源
      最近更新 更多