Thread: type cast a pointer to void

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    28

    type cast a pointer to void

    How do I type cast a pointer to void so I can use it in a loop?

    void *smMacroPtr;

    for(fooPtr = (int *)foo; fooPtr < (int *)(&foo+1); ++fooPtr, ++((int*)(smMacroPtr)))
    if (smMacroPtr != fooPtr)
    {
    cout << *smMacroPtr << " != " << *fooPtr << endl;
    break;
    }

    ++((int*)(smMacroPtr)) // this needs to be incremented but compiler still says unknown type. I tried several combinations.
    rc7j

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    An easy example:

    Code:
    #include <stdio.h>
    
    int main (void)
    {
        void *counter;
        
        for (*(int *) counter = 0; *(int *) counter < 10; (*(int *) counter)++)
        {
            printf ("%d\n", *(int *) counter);
        }
        
        return 0;   
    }
    Take notice of:

    (*(int *) counter)++

    This means that you're casting the pointer to void to a pointer to int. Since you don't want to increment the pointer, but the variable where the pointer points to, you need that '*' in front of all.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 08:57 AM