Quote:
Originally posted by nocturna_gr
What does "void*" mean in c code?
|
It means "pointer to no-specific-type".
Quote:
First this can be used both as a return value and as a parameter for a function. Can it?
|
That's correct. If it's used as a return value, the function returns a pointer to some block of memory, while not stating of which type it is. It can be used for chars, int's, binary data,..
Quote:
When do we use it? Reading some code, i have only associated it with allocated part/s of memory
|
Often it's known of which type the pointer we are dealing with and we don't use void*. But consider for example malloc() that talks to the kernel to get (allocate) a block of memory for your program. It's of course impossible for malloc() to know in advance for which type of variable you are going to use it. So malloc() returns a non-type-specific pointer: void* (see man malloc).
Sometimes it can be handy to assign a type (cast) such a block of code. E.g. if you are going to store
int's in it because int's are 4 bytes. When you have a pointer
int *idx it will advanced 4 bytes when you do
idx++, and 12 bytes if you do
idx = idx + 3.
To assign a type
int to a block of memory returned by malloc():
Code:
int *intblockpointer;
int *idx;
intblockpointer = (int*)malloc(1000 * sizeof(int));
/* Find the 0 */
idx = intblockpointer;
while (*idx <> 0) {
idx++ /* Actually advances 4 bytes (sizeof(int) == 4) */
}
free(intblockpointer);
Note: this isn't good code, it's just a short example.
It's not good because if it doesn't find a 0-int, the idx pointer goed wild.