下面的函數嘗試按升序對鏈表上的字符串進行排序。當它返回新的列表時,它將被損壞。strcpy損壞字符數組(字符串值)
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;
};
要訂購鏈接列表,您不需要執行所有這些內存分配,只要您想要移動某些東西,您應該只需更改一些「下一個」指針即可。在相關說明中,您將內存分配給'second',然後您立即使用'second = first-> next;' – lxop 2013-03-27 02:21:52
您意識到您可以交換指針,對嗎?你不必'realloc'和'strcpy'來移動它們。 – paddy 2013-03-27 02:23:39