2010-03-22 168 views
0

我有不同的结构需要以相同的方式填写。唯一的区别是它们根据不同的数据填充。将不同的结构体传递给一个函数c

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

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

任何意见将不胜感激。

+1

首先,如果它们相同,为什么会有两种不同的类型?在任何情况下,如果他们是相同的,演员就很安全。 – GManNickG 2010-03-22 23:42:30

+0

谢谢。正是我所期待的! – clear2k 2010-03-23 00:24:46

回答

1

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

在你的例子中,布局是相同的,所以它会是“安全的”......但如果其中一个结构突然改变格式并且功能没有更新以解释这种改变,那么可能会有风险。

0

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

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); 
} 
3

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

但是,这可能不是一个遍历指向未知的对象类型方便。