Say a function takes a void pointer as an argument, like so: int func(void *p);
How can we determine or guess the type of what p is pointing to?
The pointer to void can be used in generic functions in C because it is capable of pointing to any data type. One can assign the void pointer with any data type's address, and then assign the void pointer to any pointer without even performing some sort of explicit typecasting.
A void pointer is a special pointer that can point to objects of any given data type. A void pointer can be converted into a pointer of another data type by using either C-style casting or static cast.
By its definition a void pointer does not point to data of a specific type. Therefore you cannot de-reference a void pointer. First you need to cast a void pointer into a pointer of a specific type, before you can dereference it to test the value.
A void pointer can point to a variable of any data type. Here is the syntax of void pointer. Here vp is a void pointer, so you can assign the address of any type of variable to it. A void pointer can point to a variable of any data type and void pointer can be assigned to a pointer of any type.
Sure you can, and it's easy too. It's C, do whatever you want, how you want it.
Make a type system. Put everything you pass into a structure, make the first byte or two a magic number to determine what the structure contains beyond the magic number.
Make some functions to create/get/set/destroy the "typed variables".
Make some other functions to add and register new types at runtime.
Create a few defines to make it easier to read and typecast the structs.
Before you know it you will have a nice proprietary type system you can use for your projects, and it will always do EXACTLY what you want and need because YOU made it.
You could go crazy and grow it into a full object oriented like system. Or save yourself the work, and use the work of all the other people who already went crazy - http://en.wikipedia.org/wiki/GObject
In general, you can't. In some cases, if there is a guarantee on what p points to, you may be able to look at the contents at and after that address to find out. Generally, your function should know what it's being passed, unless it just passes it along.
Data and function arguments in C are just a bunch of bits lumped together. Unless you use some of those bits to tell you what the bits are, there's no consistent way to identify it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With