+ 5
How could we implement the stack ADT in C so that we could use it to store different data types at different times, instead of u
How could we implement the stack ADT in C so that we could use it to store different data types at different times, instead of using a simple code copy-and-paste approach? (I.e., how can we make our stack implementation generic?)
1 Réponse
+ 2
You could make a stack of union elements. This would be ideal for a case where each data type takes roughly the same number of bytes.
You could make a stack of void pointers(void *) and cast them to the types of pointers you want to use. This would be good if each element of your stack may be complex enough to need dynamic memory allocation.
c++ has support for generics(template classes and template functions) which would be even better for this but your question specified c which doesn't support generics. They'd be better since your variable and parameter declarations can stay precise and precisely type-checked while the implementation of your ADT stays completely generic. The lack of type checking would make your c code more like Python, PHP, or JavaScript code in that a compiler can't look for problems as well.