2013-11-02 33 views
-3

我使用C malloc函數的一個問題,當我寫:在C使用malloc不工作

int *ptr = malloc(sizeof(int)); 

或本

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

或本

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

錯誤: 'x':'int *'與'int'的間接程度不同

我正在使用Visual Studio 2013,Win32控制檯應用程序。

可能是什麼問題?

+3

int * ptr = malloc(sizeof(int));'是合適的 – 0x90

+0

那麼爲什麼它不起作用? – Nityuiop18

+0

刪除了C++標記 - 沒有必要 –

回答

1

int *ptr = malloc(sizeof(int)); 

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

在本質上是相同的(你不需要投)

無論在堆上分配足夠的內存來存儲一個int,並返回一個指向它的指針。

然而,這是....?

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

垃圾

的問題是編寫正確的代碼。

+0

#include

0

這是在堆上一個int分配內存的正確方法:

int *ptr = malloc(sizeof(int)); 

所以,你不應該有任何錯誤。如果您忘記包含標題<stdlib.h>,則應僅提供警告。但我對視覺工作室並不熟悉。另外,請檢查您是否沒有拼錯單詞malloc