void *MyConfigDetail; if (x) { ((TType1 *) MyConfigDetail) = DetailCacheBeans; } else { ((TType2 *) MyConfigDetail) = DetailailCacheHam; } </rpr> But I am unable to access the "MyConfigDetail" elements as MyConfigDetail->Forks = 22; // for example Why not?
A void pointer doesn't have a type. So it obviously don't have any elements. Assigning something to a void pointer means that you are throwing away all type information.
But this is not specific to embedded systems - do look in a good book on C or C++ programming.
And don't use any void pointers unless you really need them. The more specific data types you are using on your variables, the easier it will be to keep track of the meaning of the variable and how you may use it. void is the maximum generic you can find, so it is the #1 way to make sure that the compiler will not be able to help you.
No not use void pointers unless you know how to use C and how to use "normal" pointers. And with know, I mean "really know".
Its fixed it with
(TType1 *) MyConfigDetail->Forks = 22;
You solved it, but reduced your ability to maintain and sustain good code. Are you happy with casts littering your code when not required...?
No, it is not.
Very great care should be used when "upgrading" a pointer.
It is almost always a bad sw design if a naked pointer has to be typecast like that. You may implement a generic list with void pointers, but then you normally create a new level of abstraction to get access functions that makes sure you insert pointers of type xx, and get back pointers of type xx, in which case the code that accesses the field Forks doesn't need any type cast.
There are many great ways to write lousy code that are hard to maintain. This is one of the top-ten ways - and definitely at the top half of the list...
You said
"Are you happy with casts littering your code when not required...?"
I'm happy. my code works. Yehoooaah.
"I'm happy. my code works. Yehoooaah."
If a school assignment, then the teacher should request a rewrite or give out a "fail".
Typecasts from void pointers is required - for example to implement abstract data types. Bad use of language constructs is a big reason why so much everyday equipment regularly fail because of sw errors. Don't be happy if you get a couple of lines through the compiler. Be happy when you have a program that is well tested and easy to maintain.
Would you be happy if the car mechanic fixes your car with duct tape? If the plumber fixes your sink with a chewing gum? Right now, you are that plumber...
That's like designing a mains-powered electrical device that requires you to poke bare wires into live sockets - it will "work", but it is highly dangerous and will cause a spectacular failure with the slightest slip...