2017-09-28 252 views
-3

我正在編寫選擇第k個最小元素的算法,但編譯器報告了段錯誤11,我想知道什麼是錯誤的?什麼導致段錯誤11?原因有這麼多次舉報段故障11爲什麼會出現段錯誤11

#include <stdio.h> 

int candidate(int a[], int m, int n) { 
int j = m, c = a[m], count = 1; 

while (j < m && count > 0) { 
    j++; 
    if(a[j] == c) 
     count++; 
    else 
     count--; 

} 

if(j == n) 
    return c; 
else 
    return candidate(a, j+1, n); 
} 

int main() { 
int n, a[n],c; 
int count = 0; 
printf("Input the number of elements in the array:\n"); 
scanf("%d", &n); 
printf("Input the array elements by sequence:\n"); 

for(int i = 0; i < n; i++) 
    scanf("%d", &a[i]); 
c = candidate(a, 1, n); 
for (int j = 0; j < n; ++j) 
{ 
    if(a[j] == c) 
     count++; 
} 
if (count > n/2) 
    printf("%d\n", c); 
else 
    printf("none\n"); 


} 
+3

'int n,a [n]':'n'未初始化。 – BLUEPIXY

+0

「因爲有很多次要報告段錯誤11」:調試器需要多次查找其中斷位置的確切位置。 –

+0

但事實是,我必須輸入n作爲輸入。我如何初始化n? –

回答

0

您必須知道實際n值後,初始化數組你。

要動態初始化它,請使用HEAP存儲器和mallocfree函數與指針一起使用。

int n, *a ,c; //Declare a as pointer to array 

//Get n here with scanf... 

//Now reserve memory for array 
a = malloc(sizeof(*a) * n); 
if (a) { 
    //We have our array ready to use, use it normally 
    for(int i = 0; i < n; i++) 
     scanf("%d", &a[i]); 

    //Release memory after usage 
    free(a); 
} 
+0

Thx MAN!但是還有一個問題,我的算法在我之後仍然打印爲'none'在數組中輸入全部1,爲什麼不打印1作爲最大元素? –

+1

@LeoLi現在是調試的時候了。 – tilz0R