为什么会出现段故障11

时间:2017-09-28 07:27:44

标签: c algorithm segmentation-fault

我正在编写选择kth min元素的算法,但编译器报告了一个段错误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");


}

1 个答案:

答案 0 :(得分: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);
}