为什么指针在函数max中没有被引用?

时间:2016-11-03 12:00:40

标签: c

// function t find the max value entered in the array
    double max(double *n,int size)
    {
        int i,k=0;
        double *maxi;
        maxi=&k;

        for(i=0;i<size;i++)
        {
            if(*maxi<n[i])
            {
                maxi=&n[i];
            }
        }
        return *maxi;
    }
//elements of array are added
    main()
    {
        double a[10000],maxi;
        int size,i;
        printf("enter the size of the array");
        scanf("%d",&size);
        printf("enter the elements of array");
        for(i=0;i<size;i++)
        {
            scanf("%lf",&a[i]);
        }
        maxi=max(&a,size);
        printf("maximum value is %lf",maxi);
    }

为什么指针在函数max中没有被引用?如果我取消引用指针n,则会出错。如果有更好的方法,请建议。

2 个答案:

答案 0 :(得分:0)

n[i]*(n + i)完全相同。因此,通过[]语法取消引用指针。

至于你收到错误的原因,如果没有发布有问题的代码,就无法判断。

答案 1 :(得分:0)

将数组/指针作为参数传递并解除引用都是错误的。

maxi=max(&a,size); // passing address of the address

if(*maxi<n[i]) // k is compared to memory garbage

maxi=&n[i]; // maxi is assigned with memory garbage

请考虑以下事项:

double max( double * na, int size ) // n changed to na
{
    int idx; // changed i to idx; 
    double max; // forget about k and maxi, just simply max
    if( 0 < size )
    {
        max = na[0]; // init max to 1st elem
        for( idx = 1; idx < size; ++idx ) // iterate from 2nd elem
        {
            if( max < na[idx] ) { max = na[idx]; } // check for larger
        }
    }
    return max;
}

int main()
{
    double an[10000],maxi; // a changed to an
    // ..
    maxi = max( an, size ); // pass an not &an
    // ..
    return 0;
}