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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


or similarly:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.