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)
工作,但上面沒有?我應該怎麼做才能解決這個問題?
問題是'pairPtr-> data'但在'while'語句'NULL'檢查,因此它不應該是'NULL'。 – Pareidolia
在while語句中,您只驗證'pairPtr'不是'NULL'。您不驗證其中的'data'字段不是'NULL'。 – LiranT