2016-11-03 47 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; 
} 
相關問題