【问题标题】:Bundling Malloc Calls捆绑 Malloc 调用
【发布时间】:2019-06-28 20:55:46
【问题描述】:

我正在浏览 SO,发现 some code 向我提出了一个问题。

struct node* BuildOneTwoThree() {
struct node *list = malloc(3 * sizeof(struct node));

list[0].data = 1;
list[0].next = list+1;
list[1].data = 2;
list[1].next = list+2;
list[2].data = 3;
list[2].next = NULL;

return list;}

我试图了解这个对 malloc 的调用是如何工作的以及它返回什么。它是否返回了一个指针数组?那是怎么回事,我没想到malloc会以这种方式工作?

这似乎保证了各个结构的内存索引是一个接一个的,我认为这可能是一个强大或有用的工具。

同样在调用 malloc 之后,将数组索引初始化为

list[0] = (struct node) {1, list +1};

注意:结构节点定义为,

  struct node{
  int data;
  struct node *next;};

【问题讨论】:

  • 它返回一个指向3 * sizeof(struct node)字节分配内存的指针。
  • 为什么我可以使用数组索引来索引这些指针?
  • 因为list[i] 等价于*(list+i)
  • malloc() 在第一次调用中返回的空间足够大,可以容纳 3 个 struct node 的数组,并且指向的内存足够对齐,可以安全地将其转换为struct node * 并将其用作 3 个 struct node 值的数组。 C 标准要求保证“充分对齐”。

标签: c memory-management linked-list malloc nodes


【解决方案1】:
struct node *list = malloc(3 * sizeof(struct node));

==> 创建了三个节点结构大小的内存,并且列表指向内存存储的开始。这意味着 list=&list[0] 或 *list = list[0], list+1=&(list[1]) 或 *(list+1)=list[1], list+2=&( list[2]) 或 *(list+2)=list[2]

list[0] = (struct node) {1, list +1};

==> 是的,你可以这样做。这是我的修改方式,效果很好:

struct node* BuildOneTwoThree() {
    struct node *list = (struct node *)malloc(3 * sizeof(struct node));

    list[0] = { 1, list + 1 };
    list[1] = { 2, list + 2 };
    list[2] = { 3, NULL };
    return list;
}

【讨论】:

    【解决方案2】:

    malloc 返回一个指向指定大小的内存区域的指针。

    参数3 * sizeof(struct node) 表示区域大小能够存储3 个node 结构。

    数组中的指针和索引可以互换,如this answer 中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-04
      • 2013-12-06
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2017-08-04
      • 1970-01-01
      相关资源
      最近更新 更多