C 为什么会有段故障11

C 为什么会有段故障11,c,algorithm,segmentation-fault,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) c

我正在编写选择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");


}
#包括
整数候选(整数a[],整数m,整数n){
int j=m,c=a[m],计数=1;
而(j0){
j++;
如果(a[j]==c)
计数++;
其他的
计数--;
}
如果(j==n)
返回c;
其他的
返回候选者(a,j+1,n);
}
int main(){
int n,a[n],c;
整数计数=0;
printf(“输入数组中的元素数:\n”);
scanf(“%d”和“&n”);
printf(“按顺序输入数组元素:\n”);
对于(int i=0;in/2)
printf(“%d\n”,c);
其他的
printf(“无”);
}

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

要动态初始化它,请使用堆内存和
malloc
free
函数以及指针

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);
}
intn,*a,c//将数组声明为指向数组的指针
//在这里用scanf。。。
//现在为阵列保留内存
a=malloc(sizeof(*a)*n);
如果(a){
//我们的阵列已准备就绪,可以正常使用
对于(int i=0;i
int n,a[n]
n
未初始化。“因为报告段错误11的次数太多了”:调试器需要多少次才能找到其中断的确切位置。但事实是,我必须输入n作为输入。如何初始化n?@LeoLi在您知道n后初始化数组。对其使用
malloc
free
。C.Thx MAN中没有“分配
int
变量时自动调整其大小的数组”数据类型!但还有一个问题。在我将所有1输入数组后,我的算法仍然打印“none”。为什么不将1打印为most元素?@LeoLi该调试了。