tags:

views:

120

answers:

3

I have different structures that need to be filled out the same way. The only difference is that they are filled based on different data.

I was wondering if it's possible to pass different structures to a certain function. What I have in mind is something like:

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

Any comments will be appreciate it.

+1  A: 

In C, a pointer to a structure is simply a memory pointer. So, yes it is possible to pass a pointer to any structure to a function. However, the function would need to know the layout of the structure in order to do useful work on it.

In your example, the layout is the same, so it would be "safe" ... but it could be risky if one of the structures suddenly changed format and the function was not updated to account for that change.

Mark Wilkins
A: 

I presume you mean that the structs contain the same data types and only the names of the fields differ? If so, you have two options available to you:

1) Create a union type that contains both of these structs and pass that to some_func. It can then fill out either one of the union members - doesn't matter which one since the memory layout of the two is exactly the same, so it will have the same effect.

2) Simply have some_func take one of the structs as a parameter and when you want to pass in the other one cast it to the first one. Again, since the memory layout is the same it will work fine, ie.

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);
}
Evgeny
+3  A: 

You can do a kind of "inheritance" in C using nested structs.

Like this:

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

struct Derived_2 {
  struct Base b;
};

Then it is safe to do:

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

This is safe because it is the first member. You could of course call them in a more typesafe way at other times, like

set_base( &d.b );

But that may not be convenient in a loop over pointers to unknown object types.

Zan Lynx