首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Strdup()不工作

Strdup()不工作
EN

Stack Overflow用户
提问于 2013-02-08 18:35:00
回答 1查看 2.4K关注 0票数 0

这可能是非常基础的,每个人都会对我大喊大叫,但我已经尝试了几个小时来解决这个问题,再也受不了了。我有这样的结构

代码语言:javascript
复制
struct node
{
Key_Type element;
tree_ptr left, right;
};

我正在尝试使用strdup将一个单词放入元素中,如下所示:

代码语言:javascript
复制
newNode->element = strdup(word);

我知道它可能不工作,因为我试图分配一个指向普通变量的指针,但我不知道如何修复它。

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-08 18:51:34

根据@unwind的回答,strdup()不是一个标准的C函数,仅在POSIX投诉系统上可用。很可能您的系统中没有实现strdup

下面是strdup()的一个可能的实现

代码语言:javascript
复制
char *strdup(const char *c)
{
    char *dup = malloc(strlen(c) + 1);

    if (dup != NULL)
       strcpy(dup, c);

    return dup;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14770609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档