2017-10-16 75 views
2

因此,我正在實現基於鏈表的隊列,並將節點信息放入結構中,並將隊列的頭部和尾部放入結構中。當我嘗試添加一個節點時,我必須使用 - >兩次,並且最終得到了分段錯誤錯誤。將值設置爲雙結構指針

現在我的代碼是用戶輸入和多個選項和東西的大型程序的一部分,但我簡化了它。

typedef enum statucEnum {CALLED_AHEAD, WAITING} status; 
typedef struct nodeStruct{ 
    char* name; 
    int groupSize; 
    status inStatus;//in resturant status 
    struct nodeStruct* next; 
}Node; 

//structure to encapsulate the head of the queue along with the tail 
typedef struct headStruct{ 
    Node* head; 
    Node* tail; 
}Queue; 

void intializeQueue(Queue* queue){ 
    queue->head = NULL; 
    queue->tail = NULL; 
} 

int main(){ 
    Queue queue; 
    intializeQueue(&queue); 
    //program ask what the user wants to do, and it decides to add to the queue 
    doAdd(&queue); 
} 

void doAdd(Queue* queue){ 
    //usually the program would ask the user to input a age and name 
    int age = 4; 
    name = "v"; 
    Node* newNode; 
    newNode = malloc(sizeof(Node)); 
    newNode->groupSize = size; 
    newNode->name = name; 
    newNode->inStatus = WAITING; 
    addToList(queue, newNode); 
} 

當我使用的valgrind,它告訴我,分割故障是在這個代碼段

void addToList(Queue* queue, Node* node){ 
    printf("Address of parameter: %p", node); 
    if (queue->head == NULL){ 
     queue->head->next = node; \\this is where the error occurs 
     queue->tail->next = node; 
    }else{ 
     queue->tail->next = node; 
     queue->tail = node; 
    } 
} 

更具體在的queue->頭戴式>下一個節點=

線我似乎無法弄清楚我做錯了什麼。

+0

你檢查了NULL,然後解除了反正......你在編寫代碼之前瞭解邏輯嗎? –

回答

2

當你頭是NULL,那麼你如何設置queue-> head-> next = node ;.首先設置你的頭值,然後你可以更新你的頭下一點。所以看下面的代碼

void addToList(Queue* queue, Node* node){ 
    printf("Address of parameter: %p", node); 
    if (queue->head == NULL){ 
     queue->head = node; \\this is where the error occurs 
     queue->tail = node; 

    }else{ 
     queue->tail->next = node; 
     queue->tail = node; 
    } 
} 
+0

謝謝!編碼時我完全錯過了這一點。 –

+0

不客氣。 – Talal

1

是因爲queue->headNULL

void addToList(Queue* queue, Node* node){ 
    printf("Address of parameter: %p", node); 
    /* vvvv HERE */ 
    if (queue->head == NULL){ 
     queue->head->next = node; \\this is where the error occurs 
     queue->tail->next = node; 
    }else{ 
     queue->tail->next = node; 
     queue->tail = node; 
    } 
} 
1

顯然存在以下部分來自addToList功能的錯誤。

if (queue->head == NULL) 
{ 
    queue->head->next = node; \\this is where the error occurs 
    queue->tail->next = node; 
} 

爲前提,以該塊,queue->headnull,但在下一行queue->head通過使用queue->head->next,這是行不通的解引用。