Home > Backend Development > C++ > body text

Why Can\'t I Assign a `void*` to a Non-Void Pointer in C , But I Can in C?

Patricia Arquette
Release: 2024-10-31 11:22:29
Original
223 people have browsed it

  Why Can't I Assign a `void*` to a Non-Void Pointer in C  , But I Can in C?

void Pointers: Unveiling the Divide Between C and C

When it comes to void pointers, C and C exhibit distinct behaviors. The issue revolves around the permissibility of assigning void* return values to non-void pointers.

In C, such assignments are allowed, as exemplified by the following code that compiles without errors:

<code class="c">int* p = malloc(sizeof(int));</code>
Copy after login

However, in C , the same code fails to compile, highlighting the stricter type checking in C . This discrepancy stems from the difference in how void pointers are handled.

While C allows implicit conversions between void and any other pointer type, C restricts this freedom. In C , conversions from void to a specific pointer type require an explicit cast. So, a cast is necessary for the following code to compile in C :

<code class="c++">int* p = (int*) malloc(sizeof(int));</code>
Copy after login

Despite this difference, C does allow implicit conversions from non-void pointers to void*. This feature is evident in the following code:

<code class="cpp">void foo(void* vptr) { }

int main() {
    int* p = (int*) malloc(sizeof(int));
    foo(p);
    return 0;
}</code>
Copy after login

This code compiles without issues in both C and C. The reason lies in the inherent flexibility of void and the nature of pointers. Any object pointer can be safely converted to void without losing information. When the void* is converted back to its original pointer type, the exact pointer is restored. This is illustrated by the quote from K&R2:

"Any pointer to an object may be converted to type void * without loss of information. If the result is converted back to the original pointer type, the original pointer is recovered."

The above is the detailed content of Why Can\'t I Assign a `void*` to a Non-Void Pointer in C , But I Can in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!