2017-12-02 259 views
0

我想創建2d鏈接列表。當我嘗試訪問其元素時,會導致分段錯誤。如何創建和訪問2d鏈表元素

下面是代碼

struct Node{ 
    char *data; 
    int count; 
    struct Pair *p; 
    struct Node *next; 
}; 

struct Pair{ 
    char *data; 
    int count; 
    struct Pair *next; 
}; 

void insertPairs(char *word1, char *word2, struct Node **head){ 
struct Node *ptr = *head; 

while(ptr != NULL) { 
    if(strcmp(ptr->data, word1) == 0){ 
     struct Pair *pairPtr = ptr->p; 
     while(pairPtr != NULL){ 
      if(strcmp(pairPtr->data, word2) == 0){ //Segmentation Fault 
       pairPtr->count = pairPtr->count + 1; 
       break; 
      } 
     } 
     struct Pair *tmp = (struct Pair*) malloc(sizeof(struct Pair)); 
     tmp->data = word2; 
     tmp->count = 1; 
     tmp->next = pairPtr; 
     pairPtr = tmp; 
     break; 
    } 
    ptr = ptr->next; 
} 

} 

我做了一些調試的一部分。

這一行給了我分割故障if(strcmp(pairPtr->data, word2) == 0)

爲什麼if(strcmp(ptr->data, word1) == 0)工作,但上面沒有?我應該怎麼做才能解決這個問題?

回答

0

看着你提供的代碼我無法檢測到問題。有可能是word2pairPtr->data是空指針或不是指向空終止字節字符串的指針?在這種情況下,行爲是不確定的,很可能導致分段錯誤。

退房:http://en.cppreference.com/w/c/string/byte/strcmp

+0

問題是'pairPtr-> data'但在'while'語句'NULL'檢查,因此它不應該是'NULL'。 – Pareidolia

+0

在while語句中,您只驗證'pairPtr'不是'NULL'。您不驗證其中的'data'字段不是'NULL'。 – LiranT