2017-09-28 4 views
-3

k 번째 최소 요소를 선택하는 알고리즘을 작성하고 있지만 컴파일러가보고 한 세그먼트 오류 11이 있는데 무엇이 잘못되었는지 알고 싶습니까? 그리고 세그먼트 결함 11의 원인은 무엇입니까? 이렇게 많은 시간이 세그먼트 오류 당신은 실제 n 값을 알고 후 배열을 초기화해야한다 (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

를보고있다 원인.

동적으로 초기화하려면 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!하지만 또 하나의 질문이 남아있다. 모든 1을 배열에 입력하십시오. 왜 1을 가장 많은 요소로 인쇄하지 않습니까? –

+1

@LeoLi 디버깅 할 시간입니다. – tilz0R