【问题标题】:passing different structs to a function in c将不同的结构传递给c中的函数
【发布时间】:2010-03-22 23:40:37
【问题描述】:

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

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

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...
}

任何 cmets 都会很感激。

【问题讨论】:

  • 首先,如果它们相同,为什么会有两种不同的类型?无论如何,如果它们相同,则演员表是安全的。
  • 谢谢。正是我想要的!

标签: c function struct


【解决方案1】:

您可以使用嵌套结构在 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 );

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

【讨论】:

    【解决方案2】:

    在 C 中,指向结构的指针只是一个内存指针。所以,是的,可以将指向任何结构的指针传递给函数。但是,该函数需要知道结构的布局才能对其进行有用的工作。

    在您的示例中,布局是相同的,因此它是“安全的”......但如果其中一个结构突然更改格式并且未更新功能以解决该更改,则可能会有风险。

    【讨论】:

      【解决方案3】:

      我想你的意思是结构包含相同的数据类型,只是字段的名称不同?如果是这样,您有两种选择:

      1) 创建一个包含这两个结构的联合类型并将其传递给 some_func。然后它可以填写任何一个联合成员——不管是哪一个,因为两者的内存布局完全相同,所以会产生相同的效果。

      2) 只需让 some_func 将其中一个结构作为参数,当您想传入另一个时,将其转换为第一个。同样,由于内存布局相同,它可以正常工作,即。

      static struct stu1 **some_func(struct stu1 *not_sure_here, original_content_list)
      {
        ...
      }
      
      int main(int argc, char *argv[]) 
      {
              return_struct1 = some_func(stu1);
              return_struct2 = (struct stu2)some_func((struct stu1)stu2);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-12
        • 2015-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多