gpt4 book ai didi

c - 为什么会出现段故障11

转载 作者:行者123 更新时间:2023-11-30 21:06:54 26 4
gpt4 key购买 nike

我正在编写选择第 k 个最小元素的算法,但编译器报告了段错误 11,我想知道出了什么问题?是什么原因导致段故障11?导致多次报segment failure 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");


}

最佳答案

在知道实际的 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);
}

关于c - 为什么会出现段故障11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46463329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com