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

 

  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

 

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-27  12:30:53

posted @ 2013-11-27 12:31  虔诚的学习者  阅读(209)  评论(0编辑  收藏  举报