Home  >  Article  >  Backend Development  >  What is the difference between "void *" in C and C++?

What is the difference between "void *" in C and C++?

PHPz
PHPzforward
2023-09-02 13:17:02850browse

在C和C++中,“void *”有什么区别?

In this section, we will see the void pointer and Null pointer in C. They are both void pointers, but in C, a void pointer can be In C we cannot assign any pointer type to it but in C we have to do Explicit type conversion for assignment.

In the following example, when we write some code, we can execute these lines The code is in C.

void *p;
int *int_ptr = p;

This works fine in C. Now, if we use malloc() to allocate some memory space, we It's possible to use explicit type conversion, but if we don't do that, no problem. The malloc() The function returns a null pointer.

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

The void pointer returned here is implicitly converted to an integer type pointer.

Now if we want to run the same program in C and C, we should explicitly type cast pointer.

void *p;
int *int_ptr = (int *) p;
int *arr_ptr = (int *) malloc(sizeof(int) * 10);

The above is the detailed content of What is the difference between "void *" in C and C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete