簡體   English   中英

當我不轉換malloc的結果時,為什么編譯器會抱怨?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM