Question:

In C, what possible uses are there for initializing a void pointer?

by  |  earlier

0 LIKES UnLike

In C, what possible uses are there for initializing a void pointer?

 Tags:

   Report

2 ANSWERS


  1. The usefulness of the void pointer is that it is generic, so many functions pass it back (like malloc()). The only real thing you can do with it is maybe read things from an array as a different type or make some sort of generic function that more efficiently emulates overloading.


  2. One common use is a generic function that doesn't know what types it's dealing with. This is very common with callbacks.

    You will see this on any code that winds up in the middle of two pieces of code from the same unit. For example, the code for a browser might call into a generic network connection library. That network connection library might, if some event happens, call back into the browser. But the network connection library has no idea that it's being used by a browser. So any information that merely 'passes through' the network connection library will generally be handled as void pointers.

    The 'pthread_create' function and the analogous Windows 'AfxBeginThread' function work this way too. They have no idea what types their start functions take, so they take void pointers. In this case, application code uses the system to start a thread and call more application code. The system has no idea what type the thread will be given and what type it will accept, so it "passes through" the system in a void pointer.

    To manipulate something without knowing what it is, you store it in a void pointer. If you're just handing something from one piece of code to another, you often don't know what it is.

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions