簡體   English   中英

在c中的strtok有問題

[英]having an issue with strtok in c

我已經寫了一些代碼來幫助我在程序中消除破折號以獲得更大的鏈接列表,但是當我調用該類時,我的代碼陷入了deliminator循環中並且不會消失。 我什至無法使用kill命令殺死它,我必須打開一個新的ssh客戶端

int  deliminator(char word[], struct node *root){
    struct node *start =  (struct node*) malloc(sizeof(struct node));
    struct node *trav = (struct node*) malloc(sizeof(struct node));
    start->next= trav;
    trav->prev = start;

    char *token;
    token = strtok(word,"-");

    while(token){
            /* this loop is broken */

            printf("%s",token);
            struct node *curr  = (struct node*) malloc(sizeof(struct node));
            strcpy(curr->set, token);
            trav->next = curr;
            curr->prev = trav;
            trav = trav->next;

            token = strtok(NULL,"-");
    };
    root->next = start;
    return(0);


};

同樣,當我嘗試通過使用token = strtok(token,“-”);循環不正確地運行strtok時; 它卡在第一個令牌上。 我似乎找不到問題,我的一個朋友建議它與鏈接列表節點有關,但我刪除了它們,但遇到了同樣的問題。

我在此代碼片段中稱為deliminator類。

int main(int argc, char *argv[]){
    struct node *root = (struct node*) malloc(sizeof(struct node));
    struct node *trav = (struct node*) malloc(sizeof(struct node));
    root->next = trav;
    if(argc == 2){
    /*only one giant string*/
    deliminator(argv[1],root);
    while(root->next!= NULL){
    printf("%s",root->set);
    };

您的代碼大多結構良好,並正確使用了strtok 但是,您不會初始化變量或分配的節點內的字段。 我將您的調用從strcpy切換到strdup,以便分配內存,並使用calloc而不是malloc來將指針初始化為null。 在deliminator中,您只需要在循環內分配節點,只需要保留一個指針trav即可遍歷列表,就可以不留根節點了。

我向您請教如何不浪費根節點上的內存,而這並不是您真正需要的。 您應該只具有一個根指針,然后將其地址傳遞給分隔符。 另外,在退出之前,您應該清理並從strdup中釋放節點和分配的字符串。

int  deliminator(char word[], struct node *root) {
            struct node *trav = root;

            char *token;
            token = strtok(word,"-");

            while(token){
                            /* this loop is fixed! */

                            printf("DEBUG: %s\n",token);
                            struct node *curr  = calloc(1, sizeof(struct node));
                            curr->set = strdup(token);
                            trav->next = curr;
                            curr->prev = trav;
                            trav = trav->next;

                            token = strtok(NULL,"-");
            };
            return(0);


}

int main(int argc, char *argv[]){
            struct node *root = calloc(1, sizeof(struct node));
            if(argc == 2){
                            /*only one giant string*/
                            deliminator(argv[1],root);
                            root = root-> next;
                            while(root != NULL){
                                            printf("%s\n",root->set);
                                            root = root->next;
                            }
            }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM