首页 > 解决方案 > 将字符串复制到结构成员

问题描述

我不知道如何从 to 复制inputString字符串newNode->data

我的结构如下所示:

typedef struct node {
    char *data;
    struct node *left;
    struct node *right;
} node;

问题中的函数如下所示:

node* addToTree(char inputString[]) {
    node *newNode;

    if ((newNode = malloc(sizeof(node*))) == NULL) {
        printf("Error: could not allocate memory");
        exit(-1);
    }

    if ((newNode->data = malloc(strlen(inputString) + 1)) == NULL) {
        printf("Error: could not allocate memory");
        exit(-1);
    }

    /* This line of code doesn't seem to copy anything to newNode->data. 
       This is the way I believe should work, however I don't understand what the 
       problem with it is. I have tried strlcpy and strncpy as well. */
    strcpy(newNode->data, inputString);


    /* The line below here seems to work when I print the value
       within the function, but some of the values are garbage when
       I try to use them later on in the program. */
    newNode->data = inputString;


    newNode->left = NULL;
    newNode->right = NULL;
    printf("Input string: %s\n", inputString);
    printf("New node data: %s\n", newNode->data);

    return newNode;
}

标签: c

解决方案


您的sizeof(node*)不代表您需要的尺寸。

newnode = malloc(sizeof(node*))    // wrong
newnode = malloc(sizeof (node))    // correct
newnode = malloc(sizeof *newNode)  // better

为什么sizeof *newNode更好?

因为它可以防止在类型更改时意外忘记在两个地方更新代码

struct node {
    char *data;
    struct node *next;
    struct node *prev;
};
struct nodeEx {
    char *data;
    size_t len;
    struct nodeEx *next;
    struct nodeEx *prev;
};

struct nodeEx *newnode = malloc(sizeof (struct node)); // wrong
struct nodeEx *newnode = malloc(sizeof *newnode);      // correct

推荐阅读