为什么我在C中看到重定义错误?
问题描述:
以下是我的代码,我试图在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);
}
它给出了打开大括号功能的行上重新定义的错误。
答
在声明它之前,您可以调用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);
}
Nitty pick:在C语言中,字符串文字的元素的类型为char,而不是C++中的const char。 – 2012-04-21 14:55:50
@DanielFischer - 你能否详细说明一下?你的意思是在C中'char * a =“abc”'比'const char * a =“abc”更好吗? – MByD 2012-04-21 14:57:52
我的意思是在C中''Basic“'具有'char [6]'类型,而不是'const char [6]'。由于尝试修改字符串文字是UB,因此最好将它们分配给'const char *',但它不是语言规范所具有的类型。 – 2012-04-21 15:15:05