如何使用 calloc 初始化结构
How to use calloc to init struct
我有结构
struct Person
{
char name[50];
int citNo;
float salary;
};
现在我执行以下代码:
struct Person* p = malloc (sizeof(struct Person));
memset (p,0x00,sizeof(struct Person));
现在我想将其转换为 calloc(干净的代码),我该怎么做?
struct Person* p = calloc(sizeof(struct Person) ,1);
或者输入 1
不正确?什么是正确的方法?
来自 man7
的 calloc() 描述
#include <stdlib.h>
void *calloc(size_t nelem, size_t elsize);
The calloc()
function shall allocate unused space for an array of
nelem
elements each of whose size in bytes is elsize
. The space shall
be initialized to all bits 0
. The order and contiguity of storage
allocated by successive calls to calloc()
is unspecified. The pointer
returned if the allocation ...
我鼓励您继续阅读 link man7_calloc。
现在在阅读了上面的描述后,调用 calloc
对我来说似乎很容易:
在你的情况下,我们分配一个 struct person
的数组
struct Person* p = NULL;
struct Person* p = calloc(1, sizeof(struct Person));
您必须检查 calloc
的 return 值(如果 calloc 成功分配,如 malloc):
if(p == NULL){
puts("calloc failed");
...
...
}
我有结构
struct Person
{
char name[50];
int citNo;
float salary;
};
现在我执行以下代码:
struct Person* p = malloc (sizeof(struct Person));
memset (p,0x00,sizeof(struct Person));
现在我想将其转换为 calloc(干净的代码),我该怎么做?
struct Person* p = calloc(sizeof(struct Person) ,1);
或者输入 1
不正确?什么是正确的方法?
来自 man7
的 calloc() 描述 #include <stdlib.h>
void *calloc(size_t nelem, size_t elsize);
The
calloc()
function shall allocate unused space for an array ofnelem
elements each of whose size in bytes iselsize
. The space shall be initialized to allbits 0
. The order and contiguity of storage allocated by successive calls tocalloc()
is unspecified. The pointer returned if the allocation ...
我鼓励您继续阅读 link man7_calloc。
现在在阅读了上面的描述后,调用 calloc
对我来说似乎很容易:
在你的情况下,我们分配一个 struct person
struct Person* p = NULL;
struct Person* p = calloc(1, sizeof(struct Person));
您必须检查 calloc
的 return 值(如果 calloc 成功分配,如 malloc):
if(p == NULL){
puts("calloc failed");
...
...
}