malloc 如何在 C 中生成列表的元素?

how does malloc produce an element of a list in C?

这是我使用 ADT 结构打印列表的 C 编程课程的代码。

typedef struct list{
    int data;
    struct list *next;
}list;

int is_empty(const list *l){
    return(l==NULL);
}

void print_list(list *h, char *title){
    printf("%s\n", title);
    while(h!=NULL){
        printf("%d :", h -> data);
        h = h -> next;
    }
}

int main()
{
    list list_of_int;
    list* head = NULL;
    head = malloc(sizeof(list));
    printf("size of the list = %lu\n",sizeof(list)); //this has to be an unsigned long
    
    head -> data = 5;
    head -> next = NULL;
    
    print_list(head,"single element list");
    printf("\n\n");
    return 0;
}

我的问题是,我们如何使用 malloc() 及其创建的内存来创建列表指针头?

malloc 的目的是“使”合法 space 并提供指向它的指针。
代码中的以下行确保合法 space 包含构成节点的值。

这可能看起来很短,但仅此而已。
(而且我想你确认你现在明白了。否则我自己会认为它太短而不礼貌。)