我应该做什么来分配内存空间pNode->data
,我想在其中放入一个字符,例如pNode->data = "c"
。但它表明分段故障和内存地址pNode->data
is 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 < *(pNode->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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)