Thread: void *

  1. #1
    palette
    Guest

    void *

    Hi,


    Could someone please tell me , that if I've a function that takes a void* as an argument, then, is there any way to know, exactly which type of pointer has been passed by the calling function.

    e.g.
    Code:
       int main()
       {
           int i=5;
           func(&i);
    
           char c='c';
           func(&c);
       }
     
    
       void func(void* p)
       {
     
        // How can I know here, whether to cast p as int*, or char* to read the correct values ??
    
       }
    [code tags added by ygfperson]

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571

    Re: void *

    Originally posted by palette
    Hi,


    Could someone please tell me , that if I've a function that takes a void* as an argument, then, is there any way to know, exactly which type of pointer has been passed by the calling function.

    e.g.

    int main()
    {
    int i=5;
    func(&i);

    char c='c';
    func(&c);
    }


    void func(void* p)
    {

    // How can I know here, whether to cast p as int*, or char* to read the correct values ??

    }
    You can't, well not that I know of. Why don't you make 2 functions OR use templates. Look them up on google or here if you need further explanation.

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793

    Re: void *

    Originally posted by palette
    Hi,


    Could someone please tell me , that if I've a function that takes a void* as an argument, then, is there any way to know, exactly which type of pointer has been passed by the calling function.

    Not easilly......that's the problem with void pointers.....they strip away type info...

    There are better ways than ussing void params...

    1. Use a pointer to a base class , inherit the data you want to pass from this base class, and pass a pointer to this bas class to the function....if you have used virtual functions properly, it should work

    2. Overload the function for each type you wish to pass.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  3. game window rejected painting !
    By black in forum Windows Programming
    Replies: 4
    Last Post: 03-27-2007, 01:10 AM
  4. msvc just ate one of my source files
    By Eber Kain in forum C++ Programming
    Replies: 6
    Last Post: 07-01-2004, 05:40 AM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM