错误:'strdup'的冲突类型!

Spa*_*Fly 2 c strdup

这是"C编程语言"一书中的程序.
有一个错误:'strdup'的冲突类型!当遇到函数'strdup'时.但是如果你将'strdup'改为其他名称,例如'strdu',错误就会消失.
我不知道为什么?顺便说一下,我使用code :: blocks作为我的IDE.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define MAXWORD 100

struct tnode {
    char *word;           
    int count;           
    struct tnode *left;   
    struct tnode *right; 
};

struct tnode *addtree(struct tnode *, char *);
struct tnode *talloc(void);

void treeprint(struct tnode *);
int getword(char *, int);
char *strdup(char *);

/*  word frequency count */
int main()
{
    struct tnode *root;
    char word[MAXWORD];

    root = NULL;
    while (getword(word, MAXWORD) != EOF)
        if (isalpha(word[0]))
            root = addtree(root, word);
    treeprint(root);
    return 0;
}
/* addtree: add a node with w, at or below p */
struct tnode *addtree(struct tnode *p, char *w)
{
    int cond;
    if (p == NULL) {       /* a new word has arrived */
        p = talloc();      /* make a new node */
        p->word = strdup(w);
        p->count = 1;
        p->left = p->right = NULL;
    } else if ((cond = strcmp(w, p->word)) == 0)
        p->count++;        /* repeated word */
    else if (cond < 0)     /* less than into left subtree */
        p->left = addtree(p->left, w);
    else                   /* greater than into right subtree */
        p->right = addtree(p->right, w);
    return p;
};

/* treeprint: in-order print of tree p */
void treeprint(struct tnode *p)
{
    if (p != NULL) {
        treeprint(p->left);
        printf("%4d %s\n", p->count, p->word);
        treeprint(p->right);
    }
}

/* talloc: make a tnode */
struct tnode *talloc(void)
{
    return (struct tnode *) malloc(sizeof(struct tnode));
};

char *strdup(char *s)  /* make a duplicate of s */
{
    char *p;

    p = (char *) malloc(sizeof(strlen(s)) + 1);
    if (p != NULL)
        strcmp(p, s);
    return p;
}
.... some other function ....
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 7

你不能拥有自己的名字开头的功能str.整个"命名空间"保留在C.

在这种情况下,strdup()<string.h>函数声明与之碰撞的标准函数.

请注意,停止使用<string.h>是不够的,名称仍然保留,因此您无法有效使用它.

还有几点说明:

  1. 输入未写入,因此它应该是 const指针.
  2. 请不要malloc()在C中转换返回值.
  3. 你的strdup()工作方式非常糟糕,它的意思是strcmp()strcpy().
  4. 你的使用sizeof(strlen(s))是完全错误的,即使你解决strcmp()/ strcpy()问题也会造成大量问题.

合理的strdup()实施是:

char * my_strdup(const char *s)
{
  char *r = NULL;
  if(s != NULL)
  {
    const size_t size = strlen(s) + 1;
    if((r = malloc(size)) != NULL)
      memcpy(r, s, size);
  }
  return r;
}
Run Code Online (Sandbox Code Playgroud)

我用,memcpy()因为我知道长度,它可以更快.