![](/img/trans.png)
[英]Casting result of malloc to char (not char*) - why doesn't compiler complain?
[英]Why does the compiler complain when I do not cast the result of malloc?
我正在檢查不需要顯式地轉換malloc調用結果的代碼,但每當我嘗試這樣做時,編譯器都會拋出錯誤。
即
char *somevar;
somevar = malloc(sizeof(char) * n); //error
somevar = (char *)malloc(sizeof(char) * n); // ok
如果使用C ++編譯器而不是C編譯器,則會發生這種情況。 因為C ++需要顯式轉換。 問題不僅在於(un)轉換malloc
結果,還有任何指向其他指針的void指針。
你還記得包含函數原型嗎? 對於malloc(3),這是:
#include <stdlib.h>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.