Thread: need of void pointer

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    18

    need of void pointer

    I read up and and these are the things that confuse me.
    1)It says, a void pointer can hold the address of any data type. But pointer arithmetic is not allowed on it.

    2)Also you cannot directly dereference it, you have to assign it to a pointer of the appropriate type to dereference it.


    In that case, whats the point ? The very need of having different types of pointers is Pointer Arithmetic. for eg,
    1)int* p; p++ ; - points to the location after 2 bytes
    2)char* p; p++; - points to the next byte.
    If you were not bothered about pointer arithmetic or dereferencing it,then , even a pointer to a float can hold the address of an integer.

    For example, i tried this code, where i stored the address of an int in a pointer to a float, then passed this address back to a pointer to an integer and printed the value here. It works . So whats the point of having a void pointer ?


    Code:
    #include<stdio.h>
    #include<conio.h>
    
    int main(void)
    {
     int* pi;
     float* pf;
     int* pii;
     int a=5,sum=0;
     clrscr();
    
    
     pi=&a;
     pf=&a; 
    
     pii=pf;
    
     sum=*pi;
     //sum=*pf;   //doesnt work, shouldnt work,
     sum=*pii;
    
    
     getch();
     return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    memcpy(3): copy memory area - Linux man page
    malloc(3): Allocate/free dynamic memory - Linux man page
    Useful for when you don't really care about the details of what kind of pointer you have.

    So for example, the same malloc can be used in the same way when dealing with pointers to chars, or pointers to doubles.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Void pointers are commonly used in libraries for "user data" in callback prototypes or as members of structs. For example, pthreads are created using a prototype like this:

    Code:
    void *mythread (void *data);
    This is submitted to a library function, pthread_create() via a function pointer. One of the other arguments to pthread_create is a void*. The library creates a thread and calls the user function (which must have the prototype above) and passes it the void*. This means I, as the user of the library, can pass anything I want into a new thread:

    Code:
    struct thread_data {
         int n;
         char stuff[256];
    };
    
    void *mythread (void *p) {
          struct thread_data *data = p;  // need to do this so we can access members of the struct
          do whatever with data->stuff, etc.
    }
    
    struct thread_data eg;
    eg.n = 666;
    strcpy(eg.stuff, "hello world");
    pthread_create(mythread, (void*)&eg);   // (simplified) library call
    This way, I do not have to write a custom threading library for every task. So void pointers are actually extreme useful, more or less essential tools in C.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User \007's Avatar
    Join Date
    Dec 2010
    Posts
    179
    You can also use void pointers to get around type-safety. It's like playing Russian roulette.

  5. #5
    Registered User
    Join Date
    Jul 2011
    Posts
    18
    right, thanks for the answers,
    But what i saw was that, even if u receive the user's data, in a pointer to a float, you can still pass it to any other pointer.
    I mean,

    ptr_int = ptr_float;
    dispay(*ptr_int);

    is also valid right ?
    So y do u want to receive the user's data in a void pointer

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by tubby123 View Post
    So y do u want to receive the user's data in a void pointer
    i dnt no... mby bcause u r uing sm buf for dif typs f code as wld b t case whn rcv data from nwork...

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by tubby123 View Post
    So y do u want to receive the user's data in a void pointer
    Because "you" (the designer of the library) do not know what kind of data it will be, and don't want to restrict the user in this respect. Eg, pthreads could instead use an int* pointer, presuming all anyone will want to pass around is an array of ints, or a char* pointer, presuming all anyone will want to do is manipulate strings.

    A similar example would be a hash table or linked list implementation. These are somewhat simpler than a threading library, so very often you might write one specifically designed for a specific task. However, you could also write a generic one, eg:

    Code:
    struct node {
         struct node *next;  // singly linked list
         void *data;
    }
    What "data" is is irrelevant to most linked list functions -- insert, delete, etc. It does not have to be involved in that section of code at all. And you could use this linked list for a variety of tasks, again using the data pointer.

    Which is the same reason malloc() returns void*. Without void*, we would need a separate function to allocate memory for every possible type. This would not be such a great system, esp. since C allows for user defined types. That could be dealt with via typecasting, but using void* is a much nicer solution.

    Quote Originally Posted by \007 View Post
    You can also use void pointers to get around type-safety. It's like playing Russian roulette.
    Well -- you should be able to check the cylinder first, which takes most of "the danger" out. But given the opportunity to make a mistake, many people will...
    Last edited by MK27; 07-12-2011 at 08:34 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by tubby123 View Post
    In that case, whats the point ? The very need of having different types of pointers is Pointer Arithmetic. for eg,
    1)int* p; p++ ; - points to the location after 2 bytes
    2)char* p; p++; - points to the next byte.
    [$0.02]
    As you have read above pointers are used for much more than just performing 'pointer arithmetic'. This is due to the fact that the only real native datatype to computers is a bit, and it is either on or off. Now to actually perform something useful with computers containers have been created for these bits, specifically a byte and a word. Anything above this is an abstraction layer that is used to generate useful information such as custom datatypes as well as designating the format of these containers to provide 'higher level' native types such as a float, int, ect. Thus since it is all just bits, you only need a type definition when you want to interpret your container, aka do something with the information.
    [/$0.02]

    Also I see that you are still using Turbo-C. As a self-proclaimed ambassador for the human race I would like you to join us in this century and formally invite you to obtain a compiler that Fred Flinstone didn't create. Here are some free suggestions:

    Pelles C-great compiler and IDE, FREE, only does C.
    MSVC++ Express-great compiler and IDE, FREE, C & C++
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Yes malloc could return a pointer to any other type e.g. float*, but why should floats get special treatment? Then float would not require a cast but everything else would.
    The best thing about it though is that by returning void* nothing requires a cast (rather than everything), since void* is implicitly convertible to every other type.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Casting to pointer to pointer to void
    By Sharke in forum C Programming
    Replies: 13
    Last Post: 05-12-2009, 08:40 PM
  2. Replies: 4
    Last Post: 08-27-2007, 11:51 PM
  3. Dereference pointer to void pointer to member
    By phil in forum C Programming
    Replies: 5
    Last Post: 04-20-2005, 11:54 AM
  4. void pointer
    By studentc in forum C Programming
    Replies: 1
    Last Post: 05-17-2004, 05:15 PM
  5. void pointer
    By frenchfry164 in forum C++ Programming
    Replies: 2
    Last Post: 11-02-2003, 02:31 PM