Reputation: 555
So I have two different structs in which all the properties that I will be accessing will be the same. and I also have a function, who's argument, i want to be able to accept either of the two. Example:
typedef struct{
int whatnot = 14;
int thing[11];
} TH_CONFIG;
typedef struct{
int whatnot = 3;
int thing[5];
} TH_CONFIG_2;
*_CONFIG var;
void fun(*_CONFIG input)
{
input.whatnot = 5;
}
int main(){
fun(var);
}
I may have an inkling that I should use void as the type from that I could typecast or something?, but my searching has only yielded things about function pointers, templates, and C#.
EDIT: *_CONFIG is not meant to be syntactically correct, its signifying that I don't know what to do there, but its supposed to be the _CONFIG type
Upvotes: 0
Views: 5477
Reputation: 60848
Possible solutions.
Just pass in the arguments of the struct
you care about.
void fun(int* whatnot) { *whatnot = 5; }
int main() { fun(&myStruct.whatnot); return 0; }
Factor into a quasi-OO design.
struct { int whatnot; } typedef Common;
struct TH_CONFIG_1 { Common common; int thing[11]; };
struct TH_CONFIG_2 { Common common; int thing[5]; }
But if you insist...
void fun(void* input) {
( (int)(*input) ) = 5;
}
or...
void fun(void* input) {
( (TH_CONFIG*) input)->whatnot = 5; // may have been a TH_CONFIG_2, but who cares?
}
Note: this would not pass code review at any C shop.
Upvotes: 2
Reputation: 2159
You can use any pointer type and cast it.
If all the properties you're accessing are the same, I'm guessing one's an extension of the other (since the properties need to have the same offset from the beginning of the struct). In that case you may want to use this pattern:
struct base {
int foo;
char **strings;
};
struct extended {
struct base super;
double other_stuff;
};
Since super
is at the start of struct extended
, you can cast a struct extended *
to struct base *
without problems. Of course, you could do that by repeating the same fields in the beginning of struct extended
instead, but then you're repeating yourself.
Upvotes: 1