How does “void *” differ in C and C++?

http://www.geeksforgeeks.org/g-fact-12-2/

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

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

or similarly:

 1 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:

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

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

posted @ 2015-09-22 16:38  lyleslie  阅读(137)  评论(0编辑  收藏  举报