2015-05-24 117 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; 
}