【问题标题】:Declare and Initialize dynamic array of head nodes of linked lists声明并初始化链表头节点的动态数组
【发布时间】:2020-10-31 06:06:22
【问题描述】:

我想知道如何声明、分配和初始化Node数组为null。

typedef struct Nodes_Of_List { 
        int data; 
        struct Nodes_Of_List *next;
} Node;

//declare array of head nodes
Node *table;

//ALOCATE memory for "x" x is provided at runtime, number of head nodes
table = malloc(sizeof(Node) * x); 

//Initialize elements to Null value
?? //How to do it 

关于将链表头节点的动态数组初始化为空请求的说明。目的是制作链表数组,制作哈希表。

【问题讨论】:

  • 不清楚您要做什么。你有一个列表,还是一个列表列表?
  • Node 是指head node 吗?或者您是否需要另一个结构,例如typedef struct Head_Node { Node *head; Node *tail; } Head_Node;? (请注意,'tags' 命名空间与普通标识符命名空间是分开的,因此 struct Head_Node 不会与 Head_Node 冲突。)定义任何类型的数组与定义 int 数组的方式相同— 除非您使用不同的类型名称。如果x 是变量而不是常量,则使用malloc() 分配内存。使用calloc() 将(事实上,如果不是法律上)将分配的内存初始化为空。
  • 此链接对您有很大帮助:stackoverflow.com/questions/46320526/… 如果您需要更多详细信息,请详细说明 cmets(或编辑问题)以便我们提供帮助。
  • 你可以用table->data = NULL; table->next = NULL;初始化
  • @Lucas:因为data元素是int,所以最好不要使用NULL,而只使用0来初始化它。

标签: c pointers dynamic-memory-allocation


【解决方案1】:

根据我的理解,您想声明一个头节点数组。之后,您要将它们初始化为 NULL:

//declare array of head nodes statically
Node * table[x];      // x value provided at runtime
// Or dynamically
Node ** table = (Node **) malloc(sizeof(Node *) * x);
// Or use calloc directly wich will initialize your pointers to 0
Node ** table = (Node **) calloc(x, sizeof(Node *));

// table is an array of pointers. Each pointer references a linked list.
// Now you have just to put NULL value in each element of table
int i;
for(i = 0; i < x; i++) 
    table[i] = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 2021-06-21
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多