這是「C編程語言」一書中的程序。
有一個錯誤:'strdup'的衝突類型!當遇到函數'strdup'時。但是如果將'strdup'更改爲其他名稱,例如'strdu',則錯誤將消失。
我不知道爲什麼?順便說一下,我使用code :: blocks作爲我的IDE。錯誤:'strdup'的衝突類型!
#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 ....
另外,'s'應該聲明爲'const char *',因爲它不會修改字符串的內容(**編輯:** Ninja'd由unwind的編輯添加了代碼)。 – Medinoc
@Medinoc當然這是真的(並且在我的代碼中是「自動」的),但我也明確提到了。謝謝。 – unwind
@unwind我對「命名空間」的想法很少,顯然我不熟悉。謝謝你告訴我這些和更多的筆記! –