下面的函数尝试按升序对链表上的字符串进行排序。当它返回新的列表时,它将被损坏。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