分配时无效*

时间:2017-09-26 13:58:25

标签: c memory malloc dynamic-memory-allocation void

什么时候适合使用

void* space_to_use = malloc(size); 

1 个答案:

答案 0 :(得分:-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));