When to use a void pointer?

后端 未结 13 2025
北荒
北荒 2020-12-07 17:33

I understand the use of void pointer for malloc implementation.

void* malloc  ( size_t size );

Can anyone suggest other reasons or provide

13条回答
  •  醉话见心
    2020-12-07 18:06

    A GREAT way to learn all about void * and other C topics is to watch the first half of the fantastic Stanford "Programming Paradigms" on iTunes-U. It really explains void * (C generics) and pointers in general fantastically! It definately helped me learn C better...

    One of the biggest uses is to use void * if you want to be able to accept different types of data in a function. (heres an example: http://142.132.30.225/programming/node87.html)

    Here's a further example of what you can use them for:

      int i;
      char c;
      void *the_data;
    
      i = 6;
      c = 'a';
    
      the_data = &i;
      printf("the_data points to the integer value %d\n", *(int*) the_data);
    
      the_data = &c;
      printf("the_data now points to the character %c\n", *(char*) the_data);
    

    If you don't want to watch the free stanford classes, i'd recommend googling void pointer and reading all the material there.

提交回复
热议问题