我想问一下关于链表申请空间的问题

img

img


在定于这个链表的时候不就系统分配内存了吗,为什么头链表还需要重新申请空间,如果不申请程序就运行不起来。

定义的时候是个空指针 里面没有值,指针都是要分配内存,你看你后面加上去的那些节点都是要分配空间(也就是把你结构体的数据结构和容量给他)再赋值

供参考:

#include <stdio.h>
#include <malloc.h>
typedef struct node {
    int value;
    struct node* next;
}node;
int main()
{
    node* head, * nor, * end;
    int number, count;
    scanf("%d", &count);
    head = (node*)malloc(sizeof(node));
    head->next = NULL;                  //修改
    end = head;
    for (int i = 0; i < count; i++)
    {
        nor = (node*)malloc(sizeof(node));
        nor->next = NULL;               //修改
        scanf("%d", &number);
        nor->value = number;
        end->next =  nor;
        end = nor;
    }
    for (nor = head->next; nor != NULL; nor = nor->next) //修改
        printf("%d ", nor->value);
    return 0;
}

任何类型的数据在定义时都会涉及到两个问题,1.保存它的内存的首地址,2.存储在这个地址中的数值。指针型变量也是这样的,比如“int *a=NULL”这说明指针a暂时不指向任何地址,或者说存储这个地址的内存单元中什么都没有。你的代码中“head=(node *)mallco(sizeof(node))”也是这个意思,存储node类型指针的内存首地址已经知道了,但是内存单元里面存的什么没有人知道。