Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this C code?

#include <stdio.h>
    int main()
    {
        int i = 10;
        void *p = &i;
        printf("%d\n", (int)*p);
        return 0;
    }

 

  • A.Compile time error
  • B.Segmentation fault/runtime crash
  • C.10
  • D.Undefined behaviour

Answer: A

Correct answer: Compile time error

void is an incomplete type, so *p on a void * has no type and no size and the compiler rejects it. The cast in (int)*p comes too late: the dereference must be resolved before anything can be cast.

The correct form casts the pointer first, as *(int *)p, telling the compiler how to read the memory before reading it. That is exactly what the companion question does with a float *, and it is why void * can carry any object pointer but can be dereferenced through none.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.