malloc要不要強制轉換返回值

對於這個問題,不少人確定想固然的說必須強制轉換之類的云云……實則否則,今天看《C語言核心技術》的時候明確說到html

能夠將一個void指針值指定給另外一個對象指針數據類型;反之也行,這都不須要進行顯式數據類型轉換。

而後在c語言郵件組常見問題裏發現這個了,原文是http://c-faq.com/malloc/mallocnocast.html,內容以下:測試

Q: What's wrong with casting malloc's return value?spa

A: Suppose that you call malloc but forget to #include <stdlib.h>. The compiler is likely to assume that malloc is a function returning int, which is of course incorrect, and will lead to trouble. Now, if your call to malloc is of the formprototype

char *p = malloc(10);

the compiler will notice that you're seemingly assigning an integer to a pointer, and will likely emit a warning of the form ``assignment of pointer from integer lacks a cast'' (see question 7.6), which will alert you to the problem. (The problem is of course that you forgot to #include <stdlib.h>, not that you forgot to use a cast.) If, on the other hand, your call to malloc includes a cast:指針

char *p = (char *)malloc(10);

the compiler is likely to assume that you know what you're doing, that you really do want to convert the int returned by malloc to a pointer, and the compiler therefore probably won't warn you. But of course malloc does not return an int, so trying to convert the int that it doesn't return to a pointer is likely to lead to a different kind of trouble, which will be harder to track down.code

(Of course, compilers are increasingly likely--especially under C99--to emit warnings whenever functions are called without prototypes in scope, and such a warning would alert you to the lack of <stdlib.h> whether casts were used or not.)orm

總結一句話,C語言中的void返回值類型不須要進行強制類型轉換。(C++好像要,否則會報錯)htm

ps:對於C中不轉換會不會出問題或者警告,我測試了,沒問題,環境是MinGW對象

相關文章
相關標籤/搜索