gpt4 book ai didi

c - 将结构传递给函数以赋值

转载 作者:行者123 更新时间:2023-12-02 09:09:53 25 4
gpt4 key购买 nike

我试图将一个结构传递给驻留在单独文件中的函数。当将结构体作为参数传递时,它会抛出错误。

测试.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 中,它不会抛出任何错误并且工作得很好。但是当将函数保存在两个不同的文件中时,它给了我这些错误。

如果有人能帮助我度过难关,我将不胜感激。提前致谢。

最佳答案

error: parameter 1 (‘devanshu’) has incomplete type

这意味着结构定义对于您在其中使用它的文件不可见。除非这是故意的,否则您需要将结构体定义放在头文件中,并在每个使用该结构体的 .c 文件中包含该结构体定义。

expected ‘struct student’ but argument is of type ‘struct student *’

您编写的函数不正确。它应该是 void func(struct Student* devanshu); 并且在函数内部您应该使用 devanshu-> ... 访问成员。否则,您只需将结构的副本传递给函数,然后更改本地副本。

关于c - 将结构传递给函数以赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53667377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com