Aaquib Khan
Aaquib Khan

Reputation: 19

void *ptr = (int *)&a; does it not typecast the pointer

#include<stdio.h> 
int main() 
{ 
    int a = 12; 
    void *ptr = (int *)&a; 
    printf("%d", *ptr);
    getchar(); 
    return 0; 
}

In above code, at line void *ptr = (int *)&a; isn't the pointer is typecast to int?

Upvotes: 0

Views: 372

Answers (2)

0___________
0___________

Reputation: 67835

To make things short and easy (without citing the standard, which language does not help beginners).

  1. You can't dereference the void pointer and the compiler will emit warning and errors if you try.

  2. Assignment does not change the type of the object. void *ptr = (int *)another_pointer; doesn't change the type of the ptr. It is still void and cannot be dereferenced.

The compiler will let you know if something is not good (in most cases) like here: https://godbolt.org/z/Xm42eb

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 223795

Per C 2018 6.5.16.1 1, when the left operand has type void *, the right operand may have type int *:

One of the following shall hold… the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right…

Per 6.5.16.1 2, then right operand is automatically converted to the type of the left operand:

… the value of the right operand is converted to the type of the assignment expression…

Thus, in (int *)&a, the value of &a, which has type int *, is converted by the cast to int *, which has no effect. Then, for the assignment, it is automatically converted to void *, and the result is stored in ptr.

The type of ptr remains void *, as it is declared. C will not automatically track that the value in ptr originated from an int *.

Upvotes: 1

Related Questions