2015-05-24 52 views
-2
int maxInd (int v[], int N) 
{ 
    int max, ind; 
    for (i = 0; i < N; i++) 
    { 
     if (v[i] > v[i + 1]) { ind = i; } 
    } 
    return ind; 
} 


int main() 
{ 
    int v[10] = {1,2,3,4,5,3,7,6,8}; 
    return maxInd(v, 8); 
} 

我有這個功能,在那裏我應該回報最高INT的指數。我認爲這是正確的,因爲它沒有錯誤地運行,但它不會返回索引。詮釋的main()不返回任何

我在做什麼錯?對於初學者問題抱歉。

謝謝!

+1

這段代碼似乎很容易出現未定義的行爲:你正在從'ind'讀取,它不是(總是)初始化的。此外,它正在訪問數組越界。 –

+1

「max」變量有什麼意義? –

+0

你試過調試過嗎? – Carcigenicate

回答

2

樣品固定

int maxInd (int v[], int N){ 
    int ind = 0; 
    for(int i=0;i<N;i++){ 
     if(v[i]>v[ind]){ 
      ind=i; 
     } 
    } 
    return ind; 
} 
+0

看來,[OP想要打印值](http://stackoverflow.com/questions/30422842/int-main-doesnt-return-anything#comment48931397_30422842)。我建議在'main'中添加一個'printf'。 –

0

你的功能不會在陣列中搜索最大元素。它應該定義如下的方式

#include <stdio.h> 

size_t maxInd(const int a[], size_t n) 
{ 
    size_t max = 0; 

    for (size_t i = 1; i < n; i++) 
    { 
     if (a[max] < a[i]) max = i; 
    } 

    return max; 
} 


int main(void) 
{ 
    int a[] = { 1, 2, 3, 4, 5, 3, 7, 6, 8 }; 

    size_t max = maxInd(a, sizeof(a)/sizeof(*a)); 

    printf("The maximum element of the array is %d at position &zu\n", a[max], max); 

    return 0; 
}