包含字符串数组的结构的 malloc 问题

malloc issue with struct of containing an array of strings

我已阅读有关此问题的其他帖子。当我更改顶行时:

typedef char Key_type;

typedef string Key_type;

我在 p->key[1] = x;

处遇到内存访问错误
typedef char Key_type; // change this to string and it breaks
typedef struct node_tag{
    int count;
    Key_type key[maxSize + 1];
    struct node_tag *branch[maxSize + 1];
}Node_type;

Node_type *Insert(Key_type newkey, Node_type *root)
{
    Key_type x; /* node to be reinserted as new root    */
    Node_type *xr;  /* subtree on right of x        */
    Node_type *p;   /* pointer for temporary use        */
    Bool pushup; /* Has the height of the tree increased? */

    pushup = PushDown(newkey, root, &x, &xr);
    if (pushup) {   /* Tree grows in height.*/
        /* Make a new root: */
        p = (Node_type *)malloc(sizeof(Node_type));
        p->count = 1;
        p->key[1] = x; // memory access error
        p->branch[0] = root;
        p->branch[1] = xr;
        return p;
    }
    return root;
}

有什么小修改可以消除内存访问错误?

类 可以使用 operator new 而不是 malloc 创建。使用字符串成员时,需要做

p = new Node_type();

而不是

p = (Node_type *)malloc(sizeof(Node_type));

new运算符初始化字符串的内存。 malloc函数,不是。

您没有为您的字符串调用构造函数。另外,养成编写 C++ 而不是 C 的习惯:

typedef string Key_type;
struct Node_type{ // don't need to do typedef ...
    int count;
    Key_type key[maxSize + 1];
    Node_type *branch[maxSize + 1];
};

Node_type *Insert(Key_type newkey, Node_type *root)
{
    Key_type x; /* node to be reinserted as new root    */
    Node_type *xr;  /* subtree on right of x        */
    Node_type *p;   /* pointer for temporary use        */
    Bool pushup; /* Has the height of the tree increased? */

    pushup = PushDown(newkey, root, &x, &xr);
    if (pushup) {   /* Tree grows in height.*/
        /* Make a new root: */
        p = new Node_type;
        p->count = 1;
        p->key[1] = x; // memory access error
        p->branch[0] = root;
        p->branch[1] = xr;
        return p;
    }
    return root;
}

如果您不为结构提供构造函数,编译器将为您创建一个构造函数(以及构造构造函数)。