初始化链接结构节点

时间:2017-09-04 06:48:42

标签: c

我应该如何为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 < *(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;
}

1 个答案:

答案 0 :(得分:3)

从节点的声明,我可以看到,对于你没有分配内存的数据,你只是创建一个指向字符类型的指针,你可以按如下方式更改节点的定义(并且需要更改代码) -

typedef struct node {
char data;
int weight;
bool  end_of_key;
struct node * left;
struct node * equal;
struct node * right;} node_t;