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

CC++Server Side ProgrammingProgramming

In this section we will see what are the differences between void pointer in C and void pointer in C++. They are both void pointers but in C a void pointer can be assigned to any pointer type, but in C++, we cannot do that. In C++ we have to explicitly typecast for assigning.

In the following example these lines can be executed when we are writing some codes in C.

void *p;
int *int_ptr = p;

This will work fine in C. Now if we use malloc() to allocate some memory spaces, we can use the explicit typecast, but if we do not do that, it will also fine. The malloc() function returns void pointer.

int *int_ptr = malloc(sizeof(int) * 10);

Here the returned void pointer is implicitly converted to integer type pointer.

Now if we want to run the same program in C and C++, we should explicitly typecast the pointers.

void *p;
int *int_ptr = (int *) p;
int *arr_ptr = (int *) malloc(sizeof(int) * 10);
Published on 03-Apr-2019 11:12:19