2016-11-03 1 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 (*) [10000] ')을 전달하기보다는 배열의 첫 번째 요소에 대한 포인터 (올바른 포인터 타입'double *') '). –

답변

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; 
} 
관련 문제