2017-09-28 62 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