gpt4 book ai didi

c - 错误 : conflicting types for 'strdup' !

转载 作者:行者123 更新时间:2023-12-02 06:35:03 24 4
gpt4 key购买 nike

这是《The c programming language》一书中的程序。
出现错误:“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 ....

最佳答案

您不能拥有自己的名称以 str 开头的函数.整个“命名空间”在 C 中是保留的。

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

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

一些进一步的注意事项:

  1. 输入未写入,因此它应该是 const指针。
  2. Please don't cast the return value of malloc() in C .
  3. 你的 strdup() workalike 严重损坏,它调用 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;
}

我使用 memcpy()因为我知道长度,所以可以更快。

关于c - 错误 : conflicting types for 'strdup' !,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21850356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com