问题描述
在C语言中创建链接列表时,必须动态分配内存。因此我们可以使用malloc()
和calloc()
,但是大多数时候程序员都使用malloc()
而不是calloc()
。我不明白为什么?
这是一个节点-
struct node
{
int data;
struct node *next;
};
现在我们将使ptr正式化-
struct node *ptr = (struct node *)malloc(sizeof(struct node));
现在我们在这里使用malloc()那么为什么大多数程序员都不使用calloc()而不是malloc()。有什么区别?
解决方法
考虑一个更现实的情况:
struct person {
struct person *next;
char *name;
char *address;
unsigned int numberOfGoats;
};
struct person * firstPerson = NULL;
struct person * lastPerson = NULL;
struct person * addPerson(char *name,char *address,int numberOfGoats) {
struct person * p;
p = malloc(sizeof(struct person));
if(p != NULL) {
// Initialize the data
p->next = NULL;
p->name = name;
p->address = address;
p->numberOfGoats= numberOfGoats;
// Add the person to the linked list
p->next = lastPerson;
lastPerson = p;
if(firstPerson == NULL) {
firstPerson = p;
}
}
return p;
}
在此示例中,您可以看到calloc()
可能会毫无理由地花费CPU时间(将内存填充为零),因为结构中的每个字段始终都设置为有用的值。
如果未设置少量结构(例如numberOfGoats
保留为零),则将该字段设置为零而不是将整个内容设置为零仍然可能更快。 / p>
如果未设置大量结构,则calloc()
才有意义。
如果未设置任何结构,则您不应该为任何事情分配内存。
换句话说;在大多数情况下,calloc()
(在性能方面)较差。