简体   繁体   English

在为该结构本身调用 malloc 之后,是否需要为该结构中的其他字段调用 malloc()?

[英]Do I need to call malloc() for other field in a struct after calling malloc for that struct itself?

Let say I have a type node_t假设我有一个类型 node_t

typedef struct node{
    char* value;
    struct node *next;
}node_t;

When I want to create a new node_t pointer named n1, I call malloc当我想创建一个名为 n1 的新 node_t 指针时,我调用 malloc

node_t *n1 = malloc(sizeof(node_t));

Now I want to access and use other fields inside n1 : value and next, do I have to call malloc for these pointer again, like this:现在我想访问和使用 n1 中的其他字段:value,接下来,我是否必须再次为这些指针调用 malloc,如下所示:

n1->value = malloc(sizeof(char));
n1->next = malloc(sizeof(node_t));

Or the very first calling malloc() when creating n1 have already do all these thing ?或者在创建 n1 时第一次调用 malloc() 已经做了所有这些事情?

do I have to call malloc for these pointer again我是否必须再次为这些指针调用 malloc

It depends on how you want to use those members.这取决于您想如何使用这些成员。

When you malloc a node_t you get memory for storing 1) a char pointer and 2) a node_t pointer.当您 malloc 一个node_t您将获得用于存储 1) char指针和 2) node_t指针的node_t You can set these pointers to point to other existing objects.您可以将这些指针设置为指向其他现有对象。 But you can also set these pointers to point to new (dynamic allocated) objects.但是您也可以将这些指针设置为指向新的(动态分配的)对象。

Example 1示例 1

node_t *n1 = malloc(sizeof *n1);
assert(n1 != NULL);
n1->value = "Hello world";
n1->next = NULL;

node_t *n2 = malloc(sizeof *n2);
assert(n2 != NULL);
n2->value = "Have fun";
n2->next = NULL;

n1->next = n2;  // Create a linked list

In this example there is no direct malloc for any members of node_t .在这个例子中, node_t任何成员都没有直接的 malloc 。 The members are just set to point to other objects.成员只是设置为指向其他对象。

Example 2示例 2

node_t *n1 = malloc(sizeof *n1);
assert(n1 != NULL);
n1->value = "Hello world";

n1->next = malloc(sizeof *n1->next);
assert(n1->next != NULL);
n1->next->value = "Have fun";
n1->next->next = NULL;

This example results in the same as the first example.此示例的结果与第一个示例相同。 It's just written a little different, ie the next pointer of n1 is assigned to point to a new malloc'ed node_t instead of having a n2 object.它只是写得有点不同,即n1next指针被分配为指向一个新的node_t而不是n2对象。

Example 3示例 3

char *str1= "Hello world";
char *str2= "Have fun";

node_t *n1 = malloc(sizeof *n1);
assert(n1 != NULL);
n1->value = malloc(1 + strlen(str1));
strcpy(n1->value, str1);  // Copy the string

n1->next = malloc(sizeof *n1->next);
assert(n1->next != NULL);
n1->next->value = malloc(1 + strlen(str2));
strcpy(n1->next->value, str2);  // Copy the string
n1->next->next = NULL;

Here the value pointer is set to point to a new malloc'ed object and a copy of a string is placed in that object.这里的value指针被设置为指向一个新的 malloc 对象,并且一个字符串的副本被放置在该对象中。

So - to repeat - whether you want to malloc memory for the members depends on how you want to use the struct.所以 - 重复 - 是否要为成员分配内存取决于您想如何使用该结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM