C-为什么存在段故障11



我正在编写选择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("%dn", c);
else
    printf("nonen");

}

您必须在知道实际的n值之后初始化数组。

要动态初始化它,请与指针一起使用Heap Memory和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);
}

相关内容

  • 没有找到相关文章