簡體   English   中英

通過將某人排序到鏈表中來添加某人時出現細分錯誤的原因

[英]The reasons for segmentation fault while adding someone by sorting them into the linked list

項目清單

void MovieDatabase::  addActor(const string movieTitle, const string actorFirstName, const string actorLastName, const string actorRole ){
    bool found = false;
    Movie* temp;
    for(Movie* m= headMovie; m != NULL;  m = m-> next){
            if(m-> title == movieTitle){
                found = true;
                temp = m;
                break;
            }
    }

    if(found){
            if(headCast == NULL)
                    headCast =  new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
            else{
                    Cast *c =  new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
                    Cast *temp = headCast;
                    for(Cast* cur = headCast; cur -> next != NULL;  cur = cur -> next){
                             if(cur ->next -> lastName <  actorLastName){
                                    temp = temp -> next;
                            }
                            else{
                                    c -> next = cur -> next;
                                    temp  -> next= c;
                                    break;
                            }
                    }
            }
    }
    else
    cout << "The movie with a " << movieTitle << "  does not exist in the database,you can not add the actor. " << endl;
    size++;
}

大家好,我編輯了代碼,現在我沒有任何錯。 但是,它不顯示任何內容作為輸出。 這意味着它不會添加任何內容。 無論如何,我都會發送顯示代碼。

void MovieDatabase:: showActors(){
    for(Cast * cur= headCast;  cur != NULL; cur = cur -> next){
         cout  << cur  -> lastName << endl;
    }
}

在這段代碼中:

for(Cast* cur = headCast; cur != NULL;  cur = cur -> next){
    if(cur ->next -> lastName <  actorLastName){

您只檢查cur != NULL ,然后取消引用cur->next cur->next可能為NULL。

tempcur似乎都指向同一節點。 也許您打算一個領先於另一個,以便您有一個指向要插入的上一個節點的指針?

這是一個(未試用的)實現:

    Cast *c =  new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
    Cast *prev = NULL; // maintain a pointer to the previous node. No previous node initially.
    Cast *cur;
    for(cur = headCast; cur != NULL;  cur = cur -> next)
    {
        if(cur -> lastName > actorLastName) break; // stop if we find a place to insert.
        prev = cur;                                // update previous pointer before looping.
    }
    if(prev != NULL)
    {
        prev -> next = c; // if there is a previous node, use 'c' as its next node.
    } else {
        headCast = c;     // otherwise 'c' is the new head node.
    }
    c -> next = cur;      // the 'current' node always goes after 'c'.

暫無
暫無

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

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