c - 将字符串复制到结构成员
问题描述
我不知道如何从 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;
}
解决方案
您的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
推荐阅读
- redirect - IIS url 重定向太多重定向
- python - 布尔列的趋势
- python - 为什么导入和更新所有嵌套键时的 Python 3.6 字典表示相同的内存位置
- javascript - 在打字稿中声明 for in 循环的键类型
- c# - 在实体中插入记录时,如何重现或修复 DCRM 中的字符串截断异常?
- reactjs - 如何使用`BrowserRouter`或`MemoryRouter`监视`history`?
- wix - 如何在使用 WIX 更新安装程序时处理配置
- pytorch - CNN forward 函数,AutoTuning 层数
- html - 不能改变里面文字的颜色
- react-native - 如何在 React Native 中实现显示不同语言的字幕?