Search

Admin

6.13 — Void pointers

The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

A void pointer can point to objects of any data type:

However, because the void pointer does not know what type of object it is pointing to, it cannot be dereferenced directly! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

The next obvious questions is: If a void pointer doesn’t know what it’s pointing to, how do we know what to cast it to? Ultimately, that is up to you to keep track of.

Here’s an example of a void pointer in use:

This program prints:

5
7.5
Mollie

Void pointer miscellany

Void pointers can be set to a null value:

Although some compilers allow deleting a void pointer that points to dynamically allocated memory, doing so should be avoided, as it can result in undefined behavior.

It is not possible to do pointer arithmetic on a void pointer. This is because pointer arithmetic requires the pointer to know what size object it is pointing to, so it can increment or decrement the pointer appropriately.

Note that there is no such thing as a void reference. This is because a void reference would be of type void &, and would not know what type of value it referenced.

Conclusion

In general, it is a good idea to avoid using void pointers unless absolutely necessary, as they effectively allow you to avoid type checking. This allows you to inadvertently do things that make no sense, and the compiler won’t complain about it. For example, the following would be valid:

But who knows what the result would actually be!

Although the above function seems like a neat way to make a single function handle multiple data types, C++ actually offers a much better way to do the same thing (via function overloading) that retains type checking to help prevent misuse. Many other places where void pointers would once be used to handle multiple data types are now better done using templates, which also offer strong type checking.

However, very occasionally, you may still find a reasonable use for the void pointer. Just make sure there isn’t a better (safer) way to do the same thing using other language mechanisms first!

Quiz

1) What’s the difference between a void pointer and a null pointer?

Quiz answers

1) Show Solution

7.1 -- Function parameters and arguments
Index
6.12 -- Member selection with pointers and references

30 comments to 6.13 — Void pointers

  • sergk

    Void pointers used in custom memory allocators as well - malloc, CoTaskMemAlloc, etc.. Memory allocation routines usually don’t aware of data types they allocating memory for.

    -serg

    • V

      Note that C++ offers “new” as a type-safe way to allocate memory instead of the C malloc(). Also note that C++ offers many containers and constructs that eliminate the need for explicit new anyways, e.g.:

      Instead of:

      V

  • Noha

    is there any reason for using pointer(*) for char but reference (&) for float and int?

    • I used a pointer in the char declaration because it’s an array of chars, not just a normal char. You can also declare it like this:

      The Print() function takes a pointer as it’s first argument. In this context, the & is used to pass the address of a normal variable to a pointer parameter.

      • Danny

        This would be difficult to understand for people learning from this tutorial, since you are pointing to a literal, which you haven’t explained.

        I.e, why would a literal have an address you can point to? I’ve seen people type char * szString before, and I was hoping to understand that.

      • Hagen

        I’m struggling a bit with pointers, could someone confirm if I have understood this correctly?

        the first parameter the Print function takes is a pointer. When printing nValue and fValue, the pointer pValue is set to their addresses. However szValue has already been declared as a pointer, therefore it is passed directly into the function (?)

        • Alex

          Yup. Since szValue is already a pointer, we can just pass it in, and it will get implicitly converted to a void pointer. Since the other two aren’t pointers, we need to pass in their addresses.

  • Tom

    So you can’t do this? =[

    Thank you very much for your tutorials!

  • Henry

    I use a wide variety of materials to learn from, but this site alway cleans up the problems or questions. ty :)

  • sachin_kunal

    is dangling pointer and void pointer same

    • Alex

      No. A dangling pointer is a pointer that points to memory that has been deallocated. A void pointer is a pointer that can point to any type of data.

  • AstroBoy

    Alex,
    I’m a new user to your site. IT IS AWESOME!! I will be visiting it often. Thanks for all your hard work.

    AB

  • dim

    Congratulations for your site. It is really helpful.

  • Matti

    It would be very helpful to have some practice (e.g. programs to write) with pointers and dynamic memory allocation here!

    But thanks for a wonderful site Alex! Really fun.

  • pjhc

    why when you use:

    cout << static_cast(pValue) << endl; // without the (*) symbol, you get the whole word "molly", unlike the case you do the same but with an int type pointer, and get the direction that it is point to?

    char *szValue = "Mollie"; // here you used pointer

    or

    char szValue[] = "Mollie";
    cout<<szValue1<<endl; // it gives "mollie"

    int numbers[5]={'1','2','3','4','5' };
    cout<<numbers; // it gives 0x28fefc

  • Alex

    "Similarly, it is not possible to do pointer arithmetic on a void pointer"

    This is plain wrong! Of course you can do arithmetic on void pointers.

    • Steven

      Really? How can u do it? Show me code please.

    • Alex

      Pointer arithmetic works by incrementing or decrementing the memory address by the size of the object pointed to. Since void pointers don’t know what they’re pointing to, this doesn’t work.

      Consider:

  • Steven

    "Note that since void pointers can’t be dereferenced, there is no such thing as a void reference."
    Can u explain it more detail? To be honest, I have not thought about why there is no a void reference. I consider it’s just a kind of rule. Thanks a lot!

  • Sir

    What is the meaning of (void *)0?
    null pointer
    void pointer
    error

  • Connor

    Hello again Alex.

    Maybe I haven’t progressed far enough yet (and maybe they exist in later lessons) but do you have any exercises in regards to pointers, references, and arrays in order for us to confirm our understanding of the material?

    Thanks again

  • cpplx

    char *szValue = "Mollie";
    confussing line
    declaring a char type pointer pointing to a string?!
    im quite unexperienced to understand it.

    all i have seen so far in the lessons is
    declaring an object(?);
    declaring a pointer to that object;

  • Nope, I didn’t find any code like this: char *szValue = "Mollie";
    So, it’s not covered in lesson 6.6. A similar syntax is const char *szValue that is covered in lesson 6.8b — C-style string symbolic constants :-)

Leave a Comment

  

  

  

two × 5 =

Put C++ code inside [code][/code] tags to use the syntax highlighter