gpt4 book ai didi

c - 将不同的结构传递给c中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:38 24 4
gpt4 key购买 nike

我有不同的结构需要以相同的方式填写。唯一的区别是它们是根据不同的数据填充的。

我想知道是否可以将不同的结构传递给某个函数。我的想法是这样的:

struct stu1 {
char *a;
int b;
};

struct stu2 {
char *a;
int b;
};

static struct not_sure **some_func(struct not_sure **not_sure_here, original_content_list)
{
// do something and return passed struct
the_struct = (struct not_sure_here **)malloc(sizeof(struct not_sure_here *)20);
for(i=0; i<size_of_original_content_list; i++){
//fill out passed structure
}
return the_struct;
}

int main(int argc, char *argv[])
{
struct stu1 **s1;
struct stu2 **s2;
return_struct1 = some_func(stu1);
return_struct2 = some_func(stu2);
// do something separate with each return struct...
}

如有任何意见,我们将不胜感激。

最佳答案

您可以使用嵌套结构在 C 语言中进行某种“继承”。

像这样:

struct Derived {
struct Base b;
int another_i;
char another_c;
};

struct Derived_2 {
struct Base b;
};

那么可以安全地做:

struct Derived d;
struct Derived_2 d2;
set_base( (struct Base*)&d );
set_base( (struct Base*)&d2 );

这是安全的,因为它是第一个成员。您当然可以在其他时候以更安全的方式调用它们,例如

set_base( &d.b );

但是在指向未知对象类型的指针的循环中这可能不方便。

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

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