Friday, August 5, 2011

What does void pointer actually mean?

it's a generic pointer.

"void" is a special type, an incomplete type that cannot be completed.
You can't have an object of type void; a function that returns void
doesn't return a value.

Type "void*" is a pointer type that can point to any object. An
object of type void* can hold a value of any pointer-to-object type.
Any pointer-to-object type can be implicitly converted to void*, and vice versa.
 --------------------------------------------------------------------------------------

Basically it means "nothing" or "no type"
There are 3 basic ways that void is used:
1) Function argument: int myFunc(void) -- the function takes nothing.
2) Function return value: void myFunc(int) -- the function returns nothing
3) Generic data pointer: void* data; -- 'data' is a pointer to data of unknown type, and cannot be dereferenced

----------------------------------------------------------------------------------
There are two ways to use void:
void foo(void);
or
void *bar(void*);
The first indicates that no argument is being passed or that no argument is being returned.
The second tells the compiler that there is no type associated with the data effectively meaning that the you can't make use of the data pointed to until it is cast to a known type.
For example you will see void* used allot when you have an interface which calls a function whose parameters can't be known ahead of time.
For example, in the Linux Kernel when deferring work you will setup a function to be run at a latter time by giving it a pointer to the function to be run and a pointer to the data to be passed to the function:
struct _deferred_work {
sruct list_head mylist;
.worker_func = bar;
.data        = somedata;
} deferred_work;
Then a kernel thread goes over a list of deferred work and when it get's to this node it effectively executes:
bar(somedata);
Then in bar you have:
void bar(void* mydata) {
    int *data = mydata;
    /* do something with data */;
}
 
 
 http://stackoverflow.com/questions/1043034/what-does-void-mean-in-c-c-and-c
 

No comments:

Post a Comment