First of all, to use the malloc function, please include stdlib. H (cstdlib in C ++) instead of malloc. h. Because malloc. H has never appeared in the C or C ++ standard! Therefore, not all compilers have the malloc. h header file. However, all c compilers should have the stdlib. h header file. In C ++, it is necessary to forcibly convert the return value of malloc (); otherwise, compilation fails. However, in C, this forced conversion is redundant and is not conducive to code maintenance. At first, C had no void pointer, and char * was used as a generic pointer (generic pointer), so the return value of malloc was char *. Therefore, the return value of malloc must be forcibly converted at that time. Later, the ansi c (c89) standard defined the void pointer as a new generic pointer. Void pointers can be directly assigned to any type of pointers without conversion (except function pointers ). From then on, the return value of malloc is changed to void *, and there is no need to forcibly convert the return value of malloc. The following program is correctly compiled in vc6. # Include<Stdlib. h> Int main (void) { Double * P = malloc (sizeof * P);/* sizeof (double) is not recommended )*/ Free (P ); Return 0; } Of course, there is no error in forcibly converting the return value of malloc! For example, you may change double * P to int * P in the future. In this case, you need to change all the related (double *) malloc (sizeof (double) to (int *) malloc (sizeof (INT )). If the changes fail, your program will have bugs. Even if you are sure to get rid of all related statements, you will not like this boring job! If you do not use forced conversion, you can avoid this problem and it is easy to write. Why not? Use the following code, no matter what type the pointer is changed to in the future, no modification is required. Double * P = malloc (sizeof * P ); Similarly, when using functions such as calloc and realloc that return values as void *, you do not need to forcibly convert the return values. References: ISO/IEC 9899: 1999 (E) programming languages-C 7.20.3.3 the malloc Function ISO/IEC 9899: 1999 (E) programming ages-C p104 (6.7.2.2) Copyright of this ArticleC/C ++ standard programming for ant financialAnd the author antigloss. For details, please indicate the original author and source. Thank you. |