As I understand, void *
pointers break type safety.
This problem couldn't be solved in plain c
?
As I understand, void *
pointers break type safety.
This problem couldn't be solved in plain c
?
If "generic data structure" means a data structure that can work with arbitrary data types without the need of adapting the code, then I'd say "No".
The reason is that void *
is the only data type to which (and from which) a pointer to an arbitrary data type can be safely converted (all other pointer conversions might introduce undefined behaviour due to wrong alignment). Cf, for example, this online C draft standard:
6.3.2.3 Pointers
(1) A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
(7) A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned68) for the referenced type, the behavior is undefined. ...
So unless you reduce the "level of genericity" by allowing only particular sorts of data types (e.g. by capturing them in a common union
) or by data structures that manage memory chunks and copy them in and out with memcpy
, I'd say void*
is the way to go.