题
我很新的C,我试图实现在C二叉树将存储数字和字符串,然后打印出来了e.g。
1 : Bread
2 : WashingUpLiquid
etc.
我到目前为止的代码是:
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 300
struct node {
int data;
char * definition;
struct node *left;
struct node *right;
};
struct node *node_insert(struct node *p, int value, char * word);
void print_preorder(struct node *p);
int main(void) {
int i = 0;
int d = 0;
char def[LENGTH];
struct node *root = NULL;
for(i = 0; i < 2; i++)
{
printf("Please enter a number: \n");
scanf("%d", &d);
printf("Please enter a definition for this word:\n");
scanf("%s", def);
root = node_insert(root, d, def);
printf("%s\n", def);
}
printf("preorder : ");
print_preorder(root);
printf("\n");
return 0;
}
struct node *node_insert(struct node *p, int value, char * word) {
struct node *tmp_one = NULL;
struct node *tmp_two = NULL;
if(p == NULL) {
p = (struct node *)malloc(sizeof(struct node));
p->data = value;
p->definition = word;
p->left = p->right = NULL;
}
else {
tmp_one = p;
while(tmp_one != NULL) {
tmp_two = tmp_one;
if(tmp_one->data > value)
tmp_one = tmp_one->left;
else
tmp_one = tmp_one->right;
}
if(tmp_two->data > value) {
tmp_two->left = (struct node *)malloc(sizeof(struct node));
tmp_two = tmp_two->left;
tmp_two->data = value;
tmp_two->definition = word;
tmp_two->left = tmp_two->right = NULL;
}
else {
tmp_two->right = (struct node *)malloc(sizeof(struct node));
tmp_two = tmp_two->right;
tmp_two->data = value;
tmp_two->definition = word;
tmp_two->left = tmp_two->right = NULL;
}
}
return(p);
}
void print_preorder(struct node *p) {
if(p != NULL) {
printf("%d : %s\n", p->data, p->definition);
print_preorder(p->left);
print_preorder(p->right);
}
}
目前,它似乎工作,为int
s但说明部分只打印出所输入的最后一个。我认为它是与指针char
阵列上,但我没有运气就自己动手。任何意见或建议?
解决方案
问题是,你正在使用的字符串相同的缓冲区。请注意你的结构是抱着一个指向字符,每一次你逝去的相同字符数组为指针。
当调用scanf
在缓冲,要更改它指向,而不是指针本身的数据。
要解决这个问题,在分配给它的结构之前,你可以使用的strdup 。这样的代码行,将成为
tmp_*->definition = strdup(word);
记请,一旦你用它做的strdup通过返回的字符数组必须被释放,否则你就会有一个泄漏。
其他提示
你总是做一个scanf函数到DEF,然后传递,为您的日常插入刚刚保存指针DEF。所以,既然你所有的条目指向DEF缓存,它们都指向无论是你存储在缓冲区中的最后一个字符串。
您需要一个指针复制你的字符串,并将该副本转换为二进制树节点。
不隶属于 StackOverflow