Skip to content
Related Articles

Related Articles

Improve Article
How does “void *” differ in C and C++?
  • Difficulty Level : Easy
  • Last Updated : 29 May, 2017

C allows a void* pointer to be assigned to any pointer type without a cast, whereas C++ does not; this idiom appears often in C code using malloc memory allocation. For example, the following is valid in C but not C++:




void* ptr;
int *i = ptr; /* Implicit conversion from void* to int* */

or similarly:




int *j = malloc(sizeof(int) * 5); /* Implicit conversion from void* to int* */

In order to make the code compile in both C and C++, one must use an explicit cast:




void* ptr;
int *i = (int *) ptr;
int *j = (int *) malloc(sizeof(int) * 5);

Source:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :