初始化链接结构节点
我该怎么做才能为pNode->data
分配内存空间,我想在其中放入一个字符,如pNode->data = "c"
。 但是它显示了分段错误 , pNode->data
的内存地址是0x1
,它超出了界限。
以下是我的代码。
typedef struct node { char* data; int weight; bool end_of_key; struct node* left; struct node* equal; struct node* right; } node_t; typedef struct listnode{ char* data; int weight; struct listnode* next; } listnode_t; node_t* insert(node_t* pNode, char* word, int weight) { if(pNode == NULL) { /** * Create a new pNode, and save a character from word */ pNode = (node_t*) malloc(sizeof(*pNode)); pNode->left = NULL; pNode->equal = NULL; pNode->right = NULL; strcpy(pNode->data, word); } if(*word data)) { /** * Insert the character on the left branch */ pNode->left = insert(pNode->left, word, weight); } else if(*word == *(pNode->data)) { if(*(word+1) == '\0') { /** *set pNode end_of_key_flag to true and assign weight */ pNode->end_of_key = true; pNode->weight = weight; } else { /** * If the word contains more characters, try to insert them * under the equal branch */ pNode->equal = insert(pNode->equal, word+1, weight); } } else { /** * If current char in word is greater than char in pData * Insert the character on the right branch */ pNode->right = insert(pNode->right, word, weight); } return pNode; }
从节点的声明,我可以看到,对于没有分配内存的数据,您只是创建一个指向字符类型的指针,您可以按如下方式更改节点的定义(并且需要更改代码) –
typedef struct node { char data; int weight; bool end_of_key; struct node * left; struct node * equal; struct node * right;} node_t;