簡體   English   中英

x = malloc(n * sizeof(int)); 無法將void轉換為int

[英]x = malloc(n * sizeof (int)); cannot convert void to int

我找到了一個計算合並排序的執行時間的代碼。 我收到一條錯誤消息: “無法將void轉換為int” 我從這段代碼中得到的錯誤說x = malloc(n * sizeof (int));

    x = malloc(n * sizeof (int));

由於此問題是用C ++標記的,因此我建議使用一種完全不同的解決方案:擁抱C ++的強大功能,並使用std::vector

std::vector<int> descriptiveNameHere(n);

這種方法使您不必手動管理內存分配。 當允許vector超出范圍時,將自動釋放存儲。

關於std::vector文檔

C ++編譯器比C編譯器嚴格。 因此,並非所有C代碼都可以使用C ++編譯器進行編譯,因此,如果您不使用任何C ++功能,則不應使用C ++編譯器。

malloc返回一個void *因此,如果您使用的是C編譯器,則必須將其強制轉換為相應的類型:

Type * x = (Type *) malloc (sizeof(Type));

但是,如果必須使用C ++和malloc,則如注釋中所述,C樣式static_cast應是最后的選擇,而應使用static_cast

Type * x = static_cast<Type *>(malloc(sizeof(Type)));

您應該像這樣強制轉換malloc。

x = (int *)malloc(sizeof(int) * n)

因為malloc只是返回void指針

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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