在结构中分配一个字符串

Malloc a String in the Struct

结构看起来像这样。

struct Tree {
    int operation;
    struct Tree *left;
    struct Tree *right;
    char *value;
};

接下来,我尝试用这个函数创建一棵树:

struct Tree *new_node(int operation_new, struct Tree *left_new, struct Tree *right_new, char new_value[MAX_LENG]) {
    struct Tree *n;

    n = (struct Tree *)malloc (sizeof(struct Tree));

    if (n == NULL) {
        printf("Unable to Malloc New Structure Tree");
        exit(1);
    }
        
    n->operation = operation_new;
    n->left = left_new;
    n->right = right_new;

    // n->value = (char *)malloc(sizeof(strlen(new_value) + 1)); // -------- ( 1 )
    n->value = new_value;
    return n;
}

因此,我创建了一棵树并将其打印出来。因此,在打印树时,正确打印了 operation,即 integer。但是 value 打印不正确。也就是说,只有在树的末尾输入的值 (node) 才会到处打印。值为 String (char *)。所以我用谷歌搜索了这个问题。我找到了这个答案。

Malloc char* to store it in struct

所以我尝试了不同的方法来 malloc 这个。下面是一些示例。

// This gave me a Segmentation Fault
n->value = (char *)malloc(sizeof(strlen(new_value) + 1));
strcpy(n->value, new_value);

// This gave me a Segmentation Fault
n->value = malloc(sizeof(strlen(new_value) + 1));
strcpy(n->value, new_value);

None 给出了准确的结果!你能告诉我如何正确地 malloc 结构中的字符串吗?

要分配字符串的副本,请使用 strlen(new_value) + 1 作为传递给 malloc 的大小,传递 sizeof(strlen(new_value) + 1) 是不正确的,计算结果为 sizeof(size_t),这是常量(通常为 4 或 8,具体取决于平台)。代码是:

n->value = malloc(strlen(new_value) + 1);
if (n->value != NULL) {
    strcpy(n->value, new_value);
}

请注意这种在单个调用中分配字符串副本的更简单方法:

n->value = strdup(new_value);