아래 함수는 문자열을 연결된 목록에서 오름차순으로 정렬하려고합니다. 새 목록을 반환하면 손상됩니다.strcpy는 char 배열 (문자열 값)을 손상시킵니다.
void* order(void *ptr){
struct wordlist *head;
head = (struct wordlist *) ptr;
struct wordlist *first = (struct wordlist*)malloc(sizeof(struct wordlist));
struct wordlist *second = (struct wordlist*)malloc(sizeof(struct wordlist));
struct wordlist *temp = (struct wordlist*)malloc(sizeof(struct wordlist));
first = head;
int j = 1;
while(first != NULL){
second = first->next;
while(second != NULL){
if(strcmp(first->word, second->word) > 0){
if(temp->word == NULL){
temp->word = malloc(sizeof(first->word));
}
else{
if(realloc(temp->word, sizeof(first->word)) != NULL){
strcpy(temp->word, first->word);
}
}
if(realloc(first->word, sizeof(second->word)) != NULL){
strcpy(first->word, second->word);
}
if(realloc(second->word, sizeof(temp->word)) != NULL){
strcpy(second->word, temp->word);
}
free(temp);
}
second = second->next;
}
j++;
first = first->next;
}
}
예를 들어, 입력 후 출력은 위의 예제 코드에 시도되지
messi
ŽŽŽ
ronaldo
처럼 보이지만 그것은 당신에게 단서를 줄 것이다
piero
ronaldo
messi
될 경우 . 나는 기억의 할당과 함께 뭔가가 있다고 생각하지만 그것을 찾을 수 없었다. 그건 그렇고, 때로는 단어가 비어 있습니다.
struct wordlist{
char *word;
struct wordlist *next;
};
링크 된 목록을 정렬하려면이 메모리 할당을 모두 수행 할 필요가 없습니다. 뭔가를 이동할 때마다 '다음'포인터를 바꿀 수 있어야합니다. 관련된 메모에서'second '에 메모리를 할당하면'second = first-> next;로 즉시 이것을 유출합니다. – lxop
포인터를 바꿀 수 있다는 것을 알고 있습니까? 그들을 옮기기 위해'realloc'과'strcpy'를 할 필요가 없습니다. – paddy