2017-09-26 34 views
-2

時什麼時候適合使用void *的分配

void* space_to_use = malloc(size); 
+2

不可能複製粘貼整本C語言書中。得到任何書,答案是在第10頁。 –

+3

可以是任何你想要的 –

+0

很難從這段代碼中推斷出使用內存塊的目的。也許它不打算具體使用。 – BLUEPIXY

回答

-1
void* space_to_use = malloc(size); 
// malloc always return void pointer that means it can be typecast to any type. 
// before using void pointer it is necessary to typecast it into proper type. 
// for example:- 
// if size is 8 byte.It will allocate 8 byte of memory. 
/* 
void* space_to_use = malloc(size); 
char * ptr = (char*)space_to_use; 
*/ 
// These two line can be combine in one statement. 

char * ptr = (char*)malloc(size*sizeeof(char)); 
// NOTE:sizeof(char) is to make sure platform independent. 

// Same for int if we want to store some integer. 
int * ptr = (int*)malloc(size*sizeeof(int)); 
+2

僅供參考:'sizeof char'被定義爲始終爲'1',因此從來沒有必要通過它。但是,CHAR_BIT定義可能不同。 –

+0

另請參閱[我是否投出了malloc的結果?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –

+0

是的,它會一直是一個字節,但它將泛型整數表示爲整數*或結構變量或指針。我們需要添加sizeof(int)或sizeof(int *)或sizeof(strcuct abcd),所以如果我們提到sizeof(char),它不會損害任何東西。 – Rohit

相關問題