C语言中列表中列表的内存分配

C语言中列表中列表的内存分配,c,memory,allocation,C,Memory,Allocation,这是我第一次问一个问题,我会尽量简明扼要,我试图在一个列表中为一个列表分配空间,然后访问它的成员(int begin int end) 但是,我无法访问内部列表中的数据 patient_list->sequence->begin = 10 printf("%d",patient_list->sequence->begin) 代码以0xC0000005退出,这应该是由于如何访问内存的非法区域 为什么会发生这种情况?我只写了感兴趣的代码,因为上面的列表起

这是我第一次问一个问题,我会尽量简明扼要,我试图在一个列表中为一个列表分配空间,然后访问它的成员(int begin int end)

但是,我无法访问内部列表中的数据

patient_list->sequence->begin = 10
printf("%d",patient_list->sequence->begin)
代码以0xC0000005退出,这应该是由于如何访问内存的非法区域


为什么会发生这种情况?我只写了感兴趣的代码,因为上面的列表起作用。

您已经为
患者
结构本身分配了空间,但是该结构中的
序列
指针未初始化。您需要为该序列分配内存,如下所示

patient_list->sequence = malloc(sizeof(seq) * n);

其中
n
是列表中的条目数。如果
seq
结构中的
next
指针的目的是指向列表中的下一个条目,那么您还需要初始化列表中每个条目中的这些指针。

在读取或写入
sequence
指向的
seq
之前,您需要为其分配内存

patient_list->sequence = malloc(sizeof (seq) );
patient_list->sequence->begin = 10;
printf("%d",patient_list->sequence->begin);
如果尝试从不指向有效内存的指针读取或写入,则会出现未定义的行为,异常0xC0000005是典型的结果


请注意,
seq
在其
next
指针中仍然有一个未初始化的值,如果使用该指针,同样会造成灾难。因此,您需要仔细构建数据序列,每个条目都被初始化并指向下一个条目。

代码中有问题的部分是,您为
患者
结构分配了内存,但没有为
患者
结构中的
seq
结构分配内存。实际上,您为
序列
指针分配了内存,但没有为指针指向的位置分配内存

下面是一个简单的例子:

typedef struct patient{
    int id_patient;
    int id_medic;
    char name[15];
    float presale;
    struct seq *sequence;
}patient;

typedef struct seq{
    int begin;
    int end;
    struct seq *next;
}seq;

int main()
{
    struct patient* patient_list;
    patient_list = (patient*) malloc(sizeof(patient));
    patient_list->sequence = (seq*) malloc(sizeof(seq)); // we need to allocate the memory here
    patient_list->sequence->next = NULL;

    patient_list->sequence->begin = 10;
    printf("%d",patient_list->sequence->begin);

    return 0;
}

谢谢你!感谢你!感谢你!欣赏
typedef struct patient{
    int id_patient;
    int id_medic;
    char name[15];
    float presale;
    struct seq *sequence;
}patient;

typedef struct seq{
    int begin;
    int end;
    struct seq *next;
}seq;

int main()
{
    struct patient* patient_list;
    patient_list = (patient*) malloc(sizeof(patient));
    patient_list->sequence = (seq*) malloc(sizeof(seq)); // we need to allocate the memory here
    patient_list->sequence->next = NULL;

    patient_list->sequence->begin = 10;
    printf("%d",patient_list->sequence->begin);

    return 0;
}