can we write a function in c, tht can accept any type of array, may tht be int, float, char, struct or of any any kind, as an argument and perform some task of tht like sorting etc.
Thank you

6 Years
Discussion Span
Last Post by KenJackson

Look into how qsort() works, as that's the solution for C. However, C is very inadequate for dynamic typing, so you'd probably be better off looking for a different implementation language or ditch the "accept any type" option in favor of something better suited to C.


yes qsort is good example as deceptikon told.
Bot it is not possible to pass only array or struct, you need to tell to a function howto compare those values.
For example in qsort for struct it could be a.data > b.data


Of course you can. Declare the array parameter as a pointer to void, add a parameter that tells the function what the type is, use the type parameter in a switch statement or if-then-elses, and cast the array parameter appropriately in each case.

The afforementioned qsort function is only slight twist on this in that it requires a function parameter that works for only one type, so the case statement and casting is obviated.

Note that a template function in C++ doesn't do what you described. It just creates a separae functions for each type. And of course you can do that in C also. In fact, that would raise less objections from your peers than casting.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.