2016-11-03 50 views
-1
// 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它会给出错误。如果有更好的方法来做到这一点,请建议。为什么指针在函数max中不被取消引用?

+0

_IT给出了一个错误_并不是一个很实用的说明,请详细说明你的问题,并提供[MCVE。 –

+0

你的调用'max(&a,size)'有一个小小的差异,这可能会给你一个编译器警告。它应该是'max(a,size)'或'max(&a [0],size)'。它们都传递指向数组第一个元素的指针(这是正确的指针类型'double *'),而不是将指针传递给整个数组(这是错误的指针类型'double(*)[10000] ')。 –

回答

0

n[i]*(n + i)完全相同。所以指针通过[]语法被去引用。

至于为什么你得到一个错误,没有你张贴有问题的代码是不可能分辨的。

+0

但请注意,'&n[i];'实际上并不尊重指针。 C *必须*评估它为'n + i'。 – Bathsheba

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; 
} 
相关问题