Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c - Is it a better practice to typecast the pointer returned by malloc?

For the C code below, compare the defintions of the int pointers a and b;

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int *a=malloc(sizeof(int));
  int *b=(int *)malloc(sizeof(int));
  return(0);
}

Is it better in any way to typecast the pointer of type void, returned by the malloc function? Or is it auto-typecasted while assigning to the int pointer on the left hand side? Under which circumstances, if any, can it prove to be necessary rather than just obligatory?

Please clarify whether implicit type casting, where type of right hand side is converted to type of the left hand side, applies here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The cast is not needed for the C language, but for C++ compatibility you may want to cast. This is one of the spots where C is not a subset of C++.

The following will compile in C but not C++:

int *a=malloc(sizeof(int));

The following will compile in both C and C++:

int *b=(int *)malloc(sizeof(int));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...