C列表排序程序仅在调试后才有效

时间:2014-01-27 10:45:30

标签: c list debugging sorting structure

我写了一个小程序,它从txt文件中读取单词并将它们放在一个列表中;然后,它对单词进行排序并将它们放回文件中。当我运行程序时,它冻结,但是当我调试它时,它完美地工作。我该如何解决这个问题?

这是我的代码。从文件读取到列表并写回文件效果很好(在其他程序上检查)。我不知道如何按字母顺序对列表进行排序,以便我使用数组:

typedef struct bazaslowek                                    
{
    char *word;
    struct bazaslowek* next;
} baza;

void SORTING (baza **head)
{//================================file->list, works good
    char word[30];
    FILE *fp;
    if ((fp = fopen("bazaslow.txt", "r"))==NULL)
    {
        printf("Error while opening txt file!");
        exit(EXIT_FAILURE);
    }
    else
    {
        while(!feof(fp))
        {
            fscanf(fp,"%s\n", word);
            baza *wsk = *head;
            baza *new = malloc (sizeof(baza));
            new -> next = NULL;
            new -> word = strdup(word);
            if(wsk == NULL)
            {
                new -> next = *head;
                *head = new;
            }
            else
            {
                while(wsk -> next != NULL)
                    wsk = wsk -> next;
                wsk -> next = new;
            }
        }
    }
    fclose(fp);
    //==========================================Here's the sorting, problem is probably here

    baza *wsk= (*head);
    char tab1[31], tab2[31];
    if(wsk ->next != NULL)
        while(wsk->next != NULL)
        {
            memcpy(tab1, wsk->word, 30);
            memcpy(tab2, wsk->next->word, 30);
            if (strcmp(tab1, tab2) > 0)
            {
                memcpy(wsk->word, tab2, 30);
                memcpy(wsk->next->word, tab1, 30);
            }
            wsk = wsk->next;
        }

    //======================list->file, works good
    if ((fp = fopen("bazaslow.txt", "w"))==NULL)
    {
        printf("Error while opening file!");
        exit(EXIT_FAILURE);
    }
    else
    {
        baza *wsk = *head;
        while (wsk != NULL)
        {
            fprintf(fp, "%s\n", wsk->word);
            wsk=wsk->next;
        }
    }
    fclose(fp);
}

int main()
{
    baza *head=NULL;
    printf("Sorting time!\n");
    SORTING(&head);
    return 0;
}

我真的不知道为什么它有时会起作用,有时它不会。我已经坐了很久但却无法更改代码,因此它始终有效。有人可以帮帮我吗?怎么了?如何编写代码以使程序始终有效?

1 个答案:

答案 0 :(得分:0)

E.g sort sample

baza *outerp, *innerp;
for(outerp=*head;outerp->next != NULL;outerp=outerp->next){
    for(innerp = outerp->next;innerp != NULL;innerp=innerp->next){
        if(strcmp(outerp->word, innerp->word) > 0){
            char *tmp = outerp->word;
            outerp->word = innerp->word;
            innerp->word = tmp;
        }
    }
}