2017-10-16 59 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,这是行不通的解引用。