casting void pointers [duplicate]
Possible Duplicates:
Do I cast the result of malloc? Should I explicitly cast malloc()'s return value?
Hello,
gcc 4.4.4 c89
Normally I don't cast the return result from a malloc call.
int *int_ptr = NULL;
int_ptr = malloc(sizeof(int));
However, I have read on here, that if you cast it can hide errors. How does it hide errors if you explicitly cast to an int?
int_ptr = (int*)malloc(sizeof(int));
Also, I was reading a c programming book that stated it was good programming practice to cast from a void pointer including a call from 开发者_如何转开发malloc.
Which would be good programming practice?
int *int_ptr = NULL;
void *ptr = NULL;
int_ptr = ptr;
or
int_ptr = (int*)ptr;
Many thanks for any advice,
How does it hide errors if you explicitly cast to an int?
It can hide the error of neglecting to include stdlib.h
before you call malloc
. Without the proper function declaration, the C compiler can assume that it returns an int
, and an explicit cast will mask the fact that you're not calling malloc
properly. See Q7.6 and Q7.16 from the comp.lang.c FAQ.
Also, I was reading a c programming book that stated it was good programming practice to cast from a void pointer including a call from malloc.
Which would be good programming practice?
There is no point to explicitly casting the result of malloc
in C. It potentially masks errors, and it increases the maintenance burden (if you ever decide to change the allocated type, you now have an extra site in the code that must be altered).
The only time you should perform an explicit cast from void*
so is if you will be compiling your code as C++ since C++ does not allow that as an implicit cast. (But if you are writing C++ code, you should be using static_cast
in this case.)
Don't cast the void*
return value of malloc()
unless it is to make GCC be quiet in your environment, or if it is mandated by co-workers, etc...
Cast or no cast, void*
is only a memory address. Assigning it to a variable with a type gives it meaning, and avoiding the cast makes code easier to read.
精彩评论