下面的函数尝试按升序对链表上的字符串进行排序。当它返回新列表时,它会损坏。
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;
}
}
例如,如果输入是
piero
ronaldo
messi
然后输出看起来像
messi
ŽŽŽ
ronaldo
上面的例子没有在代码上试过,但它会给你一个线索。我相信内存分配有问题,但我无法找到它。顺便说一句,有时这些话也是空的。
另外,词表如下:
struct wordlist{
char *word;
struct wordlist *next;
};