2012-04-21 43 views
1

以下是我的代碼,我試圖在Visual Studio中運行它。爲什麼我在C中看到重定義錯誤?

#include <stdio.h> 
#include <conio.h> 
int main() 
{ 
    //int i; 
    //char j = 'g',k= 'c'; 
    struct book 
    { 
     char name[10]; 
     char author[10]; 
     int callno; 
    }; 
    struct book b1 = {"Basic", "there", 550}; 
    display ("Basic", "Basic", 550); 
    printf("Press any key to coninute.."); 
    getch(); 
    return 0; 
} 

void display(char *s, char *t, int n) 
{ 
    printf("%s %s %d \n", s, t, n); 
} 

它給出了打開大括號功能的行上重新定義的錯誤。

回答

5

在聲明它之前,您可以調用display,在這種情況下,編譯器假定返回類型爲int,但返回類型爲void

使用它之前聲明函數:

void display(char *s, char *t, int n); 
int main() { 
    // ... 

另外請注意,您聲明爲接收char*,但通過字符串字面它(const char*)或者改變聲明,或更改參數,如:

void display(const char *s, const char *t, int n); 
int main() 
{ 
    // snip 
    display ("Basic", "Basic", 550); 
    //snap 
} 

void display(const char *s, const char *t, int n) 
{ 
    printf("%s %s %d \n", s, t, n); 
} 
+0

Nitty pick:在C語言中,字符串文字的元素的類型爲char,而不是C++中的const char。 – 2012-04-21 14:55:50

+0

@DanielFischer - 你能否詳細說明一下?你的意思是在C中'char * a =「abc」'比'const char * a =「abc」更好嗎? – MByD 2012-04-21 14:57:52

+0

我的意思是在C中''Basic「'具有'char [6]'類型,而不是'const char [6]'。由於嘗試修改字符串文字是UB,因此最好將它們分配給'const char *',但它不是語言規範所具有的類型。 – 2012-04-21 15:15:05

相關問題