【问题标题】:Does array initialize memory in c? [duplicate]数组是否在c中初始化内存? [复制]
【发布时间】:2020-09-18 06:43:03
【问题描述】:

拥有这个链表:

#include <stdio.h>
#include <stdlib.h>

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

void printlist(const node_t*);
node_t *create_node(int);

int main(void){
    int values[3] = {1,2,3};
    node_t *nodes[3];
    for(int i =0; i<3 ; i++)
    {
        nodes[i] = create_node(values[i]);
        if(i!=2)
            nodes[i]->next = nodes[i+1]; //HERE, can I assign next (un)initialized node?
    }

    node_t *header = nodes[0];
    printlist(header);
}

void printlist(const node_t* header){
    for(const node_t *i = header; i; i=i->next)
        printf("value is %i\n",i->value);
}

node_t *create_node(int value){
    node_t *new = malloc(sizeof(node_t));
    new->value=value;
    new->next = 0;
    return new;
}

这给出了:

value is 1
value is 29590344

Command terminated

从输出中可以看出,第一个节点(标头)没有分配 next 结构成员,这应该发生在循环中。但我将next(指向新节点的指针)分配给数组(指向节点的指针)中的(未)初始化成员。我希望数组的初始化也应该初始化内存,当它有大小时。但真的吗?如果是这样,那么我不明白为什么分配不起作用,否则我理解并且必须实现其他循环。感谢您的回答。

【问题讨论】:

  • 由于nodes[i+1]; 尚未分配,您希望它指向哪里?您还在下一次迭代中覆盖该地址,因此您所做的在逻辑层面上也是错误的
  • “我希望数组的初始化也应该初始化内存,当它有大小时” - C 标准不同意这一点。除非您显式初始化非static 数组的值,否则它的所有成员都有 indeterminate 值
  • @UnholySheep 我肯定只分配0。所以最后一个节点对于next 将具有空值。另外,这就是问题 - 我认为数组确实初始化了每个成员的地址(这就是我的想法)。所以它没有 - 如我所见
  • @UnholySheep 好的,这可能是答案。也许一些标准的引用作为补充,但作为答案就足够了

标签: c arrays linked-list


【解决方案1】:

您的代码不会创建动态列表,因为您有一个包含 3 个节点的数组。不需要next。

你可能想要这样的东西。

/* you need to check if memory allocation was successful */

#include <stdlib.h>
#include <stdio.h>

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

void printlist(const node_t*);
node_t *append_node(node_t *, int);

int main()
{
    node_t *head = NULL, *parent = head;

    for(int x = 0; x < 10; x++)
        if(!head)
        {
            head = append_node(NULL, x);
            parent = head;
        }
        else
        {
            parent = append_node(parent, x);
        }

    printlist(head);
}

void printlist(const node_t* head){
    while(head)
    {
        printf("value is %i\n",head->value);
        head = head -> next;
    }
}

node_t *append_node(node_t *parent, int value){
    node_t *new = malloc(sizeof(*new));
    new->value=value;
    new->next = NULL;
    if(parent) parent -> next = new;
    return new;
}


【讨论】:

  • 双链表。现在我明白了为什么高级操作节点需要双链表
  • 不,它不是双重链接的。对于双链接,您需要指向前一个节点的指针。
  • 我明白了。我以为node_t *parent 是前一个指针,但它只是帮助后分配其他节点。
猜你喜欢
  • 2014-02-06
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多