In C, casting addresses through void* inside a function: what is printed? #include<stdio.h> void fun(void *p); int i; int main() { void vptr; vptr = &i; / global i zero-initialized / fun(vptr); return 0; } void fun(void p) { int q; q = (int)&p; printf("%d ", q); }

Difficulty: Medium

Correct Answer: 0

Explanation:


Introduction / Context:
This question illustrates how a function parameter of type void * can be reinterpreted by taking its own address and recasting that to int *. It is a contrived but educational example of pointer aliasing and object representation. A global int i is zero-initialized by default.


Given Data / Assumptions:

  • i is a global int → default-initialized to 0.
  • main passes vptr = &i into fun as a void .
  • Inside fun, p is a local copy of that pointer value.
  • q = (int)&p; means “treat the address of local p as if it were an int **”, so *q sees the bit pattern of p as an int *.


Concept / Approach:
*q reads the stored pointer value (which is &i), and q dereferences it to the integer i, which is 0. Although this style is unsafe and nonportable regarding strict aliasing and alignment, the intent is to show that the pointer value can be recovered.


Step-by-Step Solution:
main: vptr = &ifun: p holds &iq = (int)&pq interprets bytes of p as int → value &i**q → *(&i) → i → 0


Verification / Alternative check:
If you instead write printf("%d\n", (int)p); you also get 0 and avoid the contortion.


Why Other Options Are Wrong:
(a) Compiles in C with an explicit cast. (b) and (e) suggest randomness; the flow deterministically reads i. (d) The program prints one line with 0.


Common Pitfalls:
Assuming parameters are passed by reference; misunderstanding that p is a local copy of a pointer value; confusing type-punning with undefined behavior across incompatible representations.


Final Answer:
0

More Questions from Pointers

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion