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

Discussion

Why do we write (int *) before malloc?
     int *ip = (int *)malloc(sizeof(int));

  • A.It is for the syntax correctness
  • B.It is for the type-casting
  • C.It is to inform malloc function about the data-type expected
  • D.None of the mentioned

Answer: B

Correct answer: It is for the type-casting

The cast converts the void * that malloc returns to an int *. It tells the compiler how to treat the value; malloc itself never sees it and learns nothing about the intended type.

In C the cast is unnecessary, since void * converts implicitly to any object pointer type, and it can do harm: if stdlib.h has been forgotten, the compiler assumes a return type of int, and the cast silences the very warning that would have exposed the problem. In C++ it is required.

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

Post your comment

Please log in or register to post a comment.