如何创建和访问2d链表元素

我想创建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)工作,但上面没有?我应该怎么做才能解决这个问题?

回答:

看着你提供的代码我无法检测到问题。有可能是word2pairPtr->data是空指针或不是指向空终止字节字符串的指针?在这种情况下,行为是不确定的,很可能导致分段错误。

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

以上是 如何创建和访问2d链表元素 的全部内容, 来源链接: utcz.com/qa/258450.html

回到顶部