tags:

views:

1679

answers:

11

I understand the use of void pointer for malloc implementation.

void* malloc  ( size_t size );

Can anyone suggest other reasons or provide some scenarios where it is useful in practice.

Thanks

+2  A: 

If you are interfacing with C code and need to pass through a C++ object, but a C library will only take a generic pointer, then when you retrieve the pointer you need to re-cast it to the proper type.

Void pointers probably shouldn't be used very often, but they can help when you're trying to use a library function that works with arbitrary pointers, and doesn't really care what data is represented by that memory.

Kekoa
+1  A: 

A GREAT way to learn all about void * and other C topics is to watch the first half of the fantastic Stanford "Programming Paradigms" on iTunes-U. It really explains void * (C generics) and pointers in general fantastically! It definately helped me learn C better...

One of the biggest uses is to use void * if you want to be able to accept different types of data in a function. (heres an example: http://142.132.30.225/programming/node87.html)

Here's a further example of what you can use them for:

  int i;
  char c;
  void *the_data;

  i = 6;
  c = 'a';

  the_data = &i;
  printf("the_data points to the integer value %d\n", *(int*) the_data);

  the_data = &c;
  printf("the_data now points to the character %c\n", *(char*) the_data);

If you don't want to watch the free stanford classes, i'd recommend googling void pointer and reading all the material there.

micmoo
Yes, we get it but why don't you just create variables with the appropriate pointer type? Why go through the hassle of having to track down what type of data is stored in a void*? Why don't you just use an int* or a char*?
Kekoa
void * are the most useful when you want to make a generic function (one that takes/returns different types). You can have a function that can take ints, or doubles, or longs without having to have a function for each!
micmoo
A: 

Void pointers are useful when you write code that needs to run on multiple operating systems and needs to be fairly agnostic of underlying framework APIs.

For example, OS X, Windows and Linux all have the basic concept of a window object, but they're all very different. So I have common code that passes them around as void*'s and then platform specific implementations that cast the void* to the native type (HWND, etc).

But, yeah, as others have said in this thread, this sort of thing is certainly to be avoided except where necessary.

jeffamaphone
+3  A: 

Void pointers should be used any time the contents of a block of data is not important. For example when copying data the contents of a memory area is copied but the format of the data is not important.

Using void pointers for functions that operate on blocks of memory without needing to understand the contents it clarifies the design to users so that they know the function does not care for any data format. Often functions a coded to take a char * to handle blocks of memory when when the function is actually content agnostic.

Gerhard
A: 

Look at sqlite3_exec(). You start an SQL query and want to process the results in some way (store them into a container). You call the sqlite3_exec() and pass a callback pointer and a void* pointer to whatever object you want (container included). When sqlite3_exec() runs it calls the callback for each retrieved row and passed that void* pointer into it so the callback can cast the pointer and do whatever you intended.

The important thing is that sqlite3_exec() doesn't care what the callback does and what pointer you pass. void* is exactly for such pointers.

sharptooth
+6  A: 

One good scenario of use void* is when you want to implement any generic ADT's, in case you just don't know what datatype it going to keep and deal with. For example linked list like following:

typedef struct node_t node;
struct
{
    void* data;
    node* prev, next;
} note_t;

typedef struct list_t list;
typedef void* (func)(void*) cpy_func;
typedef void (func)(void*) del_func;
struct
{
   node* head, tail, curr;
   cpy_func copy;
   del_func delete;
} list_t;

initializeLinkedList( cpy_func cpy, del_func del);
//here you keep going defining an API

Here for example you will pass in initialization function pointers to other functions which will be capable to copy you datatype to your list and free them afterwards. So by using void* you make you list more generic.

And I think void* remained in C++ only because on backward compatibility, since in C++ you have more safe and sophisticated way's to achieve same result like templates, functors and etc...As well you don't need to use malloc while programming C++, so regarding C++ I don't have any specific useful examples.

Artem Barger
Thanks Artem.Thats the thing. also in case of C, same thing can be implemented using char*. I was unable to think of a scenario where a char* cannot be used instead. (applies to malloc ).
Mac13
The C++ idiom is to use templates, and the standard library provides a good many useful ones (including a linked list).
David Thornley
Using `void*` instead of `char*` provides a certain measure of type safety. You are telling the compiler "I should never be allowed to dereference one of these pointers."
Novelocrat
+1  A: 

It is commonly used in numerical code, for example a C root solver function might look like that:

double find_root(double x0, double (*f)(double, void*), void* params)
{
/* stuff */
y = f(x, params);
/* other stuff */
}

params is cast by f to some structure it knows about, but find_root doesn't.

quant_dev
More generally, `void*` make good arguments to callback functions and various other things where someone will need to pass a function an argument, but shouldn't need to know the type of that argument.
Novelocrat
A: 

Another example of such C "generics", implemented with void *, is a standard qsort function:

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

You can sort an array of any type: int, long, double, char * or some struct pointers...

Tomek Szpakowicz
A: 

Next to interfacing with C, I find myself only using void pointers when I need to debug / trace some code and like to know the address of a certain pointer.

SomeClass * myInstance;
// ...
std::clog << std::hex << static_cast< void* >(myInstance) << std::endl;

Will print something like

0x42A8C410

And, in my opinion, nicely documents what I'm trying to do (know the pointer address, not anything about the instance)

Pieter
A: 

int (*f) (void);

f =(void*) getprocaddress(dll,"myfunction");

to make the compiler happy

Arabcoder
This won't compile. How is it going to make the compiler happy is completely unclear.
AndreyT
A: 

void * is really a C-ism, and allows C to do some things that it could not reasonably do otherwise.

char * cannot portably be used for anything, as different platforms can make different types of pointers - a char * isn't necessarily handled (or even the same size as) a void *.

So when the type of data isn't known in C (or is polymorphic or otherwise dynamic), then void * allows you to generate the correct underlying pointer type - one that can point to anything correctly.

In C++ void* generally should never come up except in the context of interfacing with legacy C code in one form or another.

Mordachai