c - 分配时为空*

标签 c memory malloc dynamic-memory-allocation void

什么时候适合使用

void* space_to_use = malloc(size); 

最佳答案

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));

关于c - 分配时为空*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428491/

相关文章:

C分配内存失败

c - 这个字符应该是无符号的吗?

Django:select_lated() 和内存使用

Linux:由于虚拟内存限制,无法在单个进程中分配超过 32 GB/64 GB 的内存

C内存分配问题

c - 如何释放从另一个函数返回的 char*?

c - 在 C 中验证输入

c - 如何检查C中的缓冲区?

c - 获取 BORLAND c 的当前时间

python - 在python中使Eratosthenes筛分更有效的内存?