这可能是非常基础的,每个人都会对我大喊大叫,但我已经尝试了几个小时来解决这个问题,再也受不了了。我有这样的结构
struct node
{
Key_Type element;
tree_ptr left, right;
};我正在尝试使用strdup将一个单词放入元素中,如下所示:
newNode->element = strdup(word);我知道它可能不工作,因为我试图分配一个指向普通变量的指针,但我不知道如何修复它。
Table insert(Key_Type word,Table root)
{
struct node *newNode = malloc(sizeof(struct node));
struct node *left = malloc(sizeof(struct node));
struct node *right = malloc(sizeof(struct node));
newNode = root->head;
//fprintf (stderr, "Hi\n");
while(newNode->element != NULL)
{
//printf("%s",word);
if(strcmp(word,newNode->element) == 0)
{
fprintf (stderr, "Hi\n");
return root;
}
while(strcmp(word,newNode->element) == -1)
{
//fprintf (stderr, "Hi\n");
newNode = newNode->left;
//fprintf (stderr, "Hi\n");
}//if
//fprintf (stderr, "Hi\n");
while(strcmp(word,newNode->element) == 1)
{
//fprintf (stderr, "Hi\n");
newNode = newNode->right;
//fprintf (stderr, "Hi\n");
}//else if
}
//createNode(word);
newNode->element = strdup(word);
newNode->left = left;
newNode->right = right;
//fprintf (stderr, "Hi\n");
//printf("%s",root->head->element);
return root;
}发布于 2013-02-08 18:51:34
根据@unwind的回答,strdup()不是一个标准的C函数,仅在POSIX投诉系统上可用。很可能您的系统中没有实现strdup。
下面是strdup()的一个可能的实现
char *strdup(const char *c)
{
char *dup = malloc(strlen(c) + 1);
if (dup != NULL)
strcpy(dup, c);
return dup;
}https://stackoverflow.com/questions/14770609
复制相似问题