【发布时间】:2019-05-09 02:13:51
【问题描述】:
我正在尝试将结构传递给驻留在单独文件中的函数。将结构体作为参数传递时,会引发错误。
Test.c
struct student{
int rollNumber;
unsigned char name[20];
int marks;
};
void func(struct student devanshu);
int main(){
struct student devanshu;
func(&devanshu);
printf("--------------------%d\n", devanshu.rollNumber);
printf("--------------------%d\n", devanshu.marks);
printf("--------------------%s\n", devanshu.name);
}
NewTest.c:
void func(struct student devanshu)
{
devanshu.rollNumber = 1;
devanshu.marks = 909;
strcpy(devanshu.name, "abc.xyz");
return;
}
这是我得到的输出:
In file included from test.c:6:0:
newtest.c:10:30: error: parameter 1 (‘devanshu’) has incomplete type
void func(struct student devanshu)
test.c: In function ‘main’:
test.c:23:7: error: incompatible type for argument 1 of ‘func’
func(&devanshu);
^
In file included from test.c:6:0:
newtest.c:10:6: note: expected ‘struct student’ but argument is of type ‘struct student *’
void func(struct student devanshu)
newtest.c:10:30: error: parameter 1 (‘devanshu’) has incomplete type
void func(struct student devanshu)
newtest.c:7:20: error: storage size of ‘devanshu’ isn’t known
struct student devanshu;
如果我在同一个文件(即test.c)中使用该函数,它不会抛出任何错误并且工作正常。但是当将函数保存在两个不同的文件中时,它会给我这些错误。
如果有人能帮助我度过难关,将不胜感激。提前致谢。
【问题讨论】:
-
C 是严格按值传递的。想想影响。
-
好吧,真正的问题是 什么 是按值传递的。在这方面,C 语言中结构和数组的传递 syntax 如何看起来 是相同的,但编译器对这种语法的理解却完全不同.这就是为什么我称它为“陷阱”。