2014-02-18 66 views
2

這是「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 .... 

回答

7

您不能擁有自己的名字以str開頭的功能。整個「命名空間」保留在C中。

在這種情況下,strdup()<string.h>的標準函數,它與您的函數聲明發生衝突。

請注意,停止使用<string.h>是不夠的,名稱仍保留,因此您無法有效使用它。

一對夫婦的進一步說明:

  1. 輸入不被寫入,所以它應該是一個const指針。
  2. Please don't cast the return value of malloc() in C
  3. Your strdup() workalike is horribly broken,it called strcmp() When it's 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(),因爲我知道的長度,它可以更快。

+0

另外,'s'應該聲明爲'const char *',因爲它不會修改字符串的內容(**編輯:** Ninja'd由unwind的編輯添加了代碼)。 – Medinoc

+0

@Medinoc當然這是真的(並且在我的代碼中是「自動」的),但我也明確提到了。謝謝。 – unwind

+0

@unwind我對「命名空間」的想法很少,顯然我不熟悉。謝謝你告訴我這些和更多的筆記! –

2

strdup已經在string.h中定義了。只需重命名你的功能。