【问题标题】:Void* when allocating [closed]分配时无效* [关闭]
【发布时间】:2018-03-07 19:08:32
【问题描述】:

什么时候适合使用

void* space_to_use = malloc(size); 

【问题讨论】:

  • 不可能复制粘贴整本 C 书。获取任何书籍,答案在前 10 页。
  • 可以是你想要的任何东西
  • 请说明您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • 在提交答案后完全更改您的问题有点粗鲁,因为现在答案没有意义。
  • 需要回答您在何处找到此代码的一些上下文。

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


【解决方案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));

【讨论】:

  • 仅供参考:sizeof char 被定义为始终为1,因此无需重复使用它。但是,CHAR_BIT 定义可以不同。
  • 是的,它总是一个字节,但它对于整数 * 或结构 varaibe 或指针的整数表示通用。我们需要添加 sizeof(int) 或 sizeof(int *) 或 sizeof(strcuct abcd ) 所以如果我们提到 sizeof(char) 它不会伤害任何东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2019-06-28
  • 2013-03-30
  • 1970-01-01
相关资源
最近更新 更多