나는 C를 처음 접했고 char 포인터 배열과 함께 qsort ()를 사용하려고합니다. 예상대로 배열을 알파벳순으로 정렬하지 않고 첫 번째 요소를 제거합니다. 비교 기능을 포함한 모든 인수를 조정하려고 시도했지만 무엇이 잘못되었는지 파악할 수 없었습니다.
단어 입력 : foo
단어 입력 : bar
단어 입력 : baz
단어 입력 : quux
예상 :
bar
baz
foo
quux
결과:
Bar
Baz
Quux
내 코드 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 10
#define MAX_LENGTH 20
int read_line(char str[], int n);
int compare(const void *a, const void *b);
int main(void) {
char *words[MAX_WORDS], word[MAX_LENGTH + 1];
int i;
for(i = 0; i < MAX_WORDS; i++) {
printf("Enter word: ");
read_line(word, MAX_LENGTH);
words[i] = malloc(strlen(word) + 1);
if(!words[i]) {
printf("Allocation of memory failed...\n");
exit(EXIT_FAILURE);
}
strcpy(words[i], word);
if(!strlen(words[i]))
break;
}
qsort(words[0], i, sizeof(char *), compare);
for(int j = 0; j <= i; j++) {
printf("%s\n", words[j]);
}
return 0;
}
int read_line(char str[], int n) {
int ch, i;
while((ch = getchar()) != '\n') {
if(i < n)
str[i++] = ch;
}
str[i] = '\0';
return i;
}
int compare(const void *a, const void *b) {
return strcmp((char *) a, (char *) b);
}
세 가지 오류.
qsort
정렬되는 배열의 첫 번째 요소에 대한 포인터가 필요합니다.
바꾸다
qsort(words[0], i, sizeof(char *), compare);
와
qsort(&( words[0] ), i, sizeof(char *), compare);
아니면 그냥
qsort(words, i, sizeof(char *), compare);
이 후자의 버전은 포인터가 예상되는 곳에 사용 된 배열이 첫 번째 요소에 대한 포인터로 붕괴되기 때문에 작동합니다.
비교 함수는 정렬되는 배열의 요소에 대한 포인터를 전달합니다. 포인터 배열을 정렬하고 있기 때문에 비교 함수가 해당 포인터 ( char**
)에 대한 포인터를 전달한다는 의미 입니다. 이와 같이 compare
해야한다
static int compare(const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}
더 나은 :
static int compare(const void *a, const void *b) {
return strcmp(*(char * const *)a, *(char * const *)b);
}
최종 루프에 패스가 너무 많습니다.
경우 i<MAX_WORDS
(때문에 (빈 라인을 입력했기 때문에),이 방출되는 빈 줄의 원인이됩니다 words[i]
길이가 0 인 문자열을 포함). 인 경우 정의되지 않은 동작을i==MAX_WORDS
호출합니다 ( 배열의 끝을 벗어 났기 때문 ).words[i]
바꾸다
for(int j = 0; j <= i; j++)
와
for(int j = 0; j < i; j++)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다