2017-09-26 94 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

相关问题