Skip to main content
Engineering LibreTexts

2.9: Void Pointers

  • Page ID
    34654
  • There is some additional discussion of Void Pointers

    This is a special type of pointer available in C++ which represents absence of type. void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties).

    This means that void pointers have great flexibility as it can point to any data type. There is payoff for this flexibility. These pointers cannot be directly dereferenced. They have to be first transformed into some other pointer type that points to a concrete data type before being dereferenced. This transformation is called casting in C++. Notice in the following example - the first function, there is a void pointer for *data, BUT, in the if statement this variable is cast to a (char *). This forces the variable *data to be a char*. This is important for use of void pointers.

    // C++ program to illustrate Void Pointer in C++ 
    #include <iostream> 
    using namespace std;
    
    void increase(void *data, int ptrsize) 
    { 
        if(ptrsize == sizeof(char)) 
        { 
            char *ptrchar; 
    
            //Typecast data to a char pointer 
            ptrchar = (char*)data; 
    
            //Increase the char stored at *ptrchar by 1 
            (*ptrchar)++; 
            cout << "*data points to a char"<<"\n"; 
        } 
        else if(ptrsize == sizeof(int)) 
        { 
            int *ptrint; 
    
            //Typecast data to a int pointer 
            ptrint = (int*)data; 
    
            //Increase the int stored at *ptrchar by 1 
            (*ptrint)++; 
            cout << "*data points to an int"<<"\n"; 
         } 
    } 
    
    int main() 
    { 
       // Declare a character 
       char c='x'; 
    
       // Declare an integer 
       int i=10; 
    
       //Call increase function using a char and int address respectively 
       increase(&c,sizeof(c)); 
       cout << "The new value of c is: " << c <<"\n"; 
       
       increase(&i,sizeof(i)); 
       cout << "The new value of i is: " << i <<"\n"; 
       
       return 0;
    
    }

    Output:

    *data points to a char

    The new value of c is: y

    *data points to an int

    The new value of i is: 11

    Adapted from:
    "Pointers in C/C++ with Examples" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY 4.0