如何解决C中列表中列表的内存分配
我是第一次问一个问题,我会尽量简洁,我试图为列表中的列表分配空间,然后访问其成员( int begin int end )。
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;
struct patient* patient_list;
patient_list = malloc(sizeof(patient));
但是我无法访问内部列表中的数据
patient_list->sequence->begin = 10
printf("%d",patient_list->sequence->begin)
代码以 0xC0000005 退出,这应该是由于如何访问非法内存区域。
为什么会发生这种情况?我只写了感兴趣的代码,因为上面的列表有效。
解决方法
您已为 patient
结构本身分配了空间,但该结构中的 sequence
指针未初始化。您需要为该序列分配内存,例如
patient_list->sequence = malloc(sizeof(seq) * n);
其中 n
是列表中的条目数。如果 next
结构中的 seq
指针的意图是指向列表中的下一个条目,您还需要在列表的每个条目中初始化这些指针。
在读取或写入 seq
指向的 sequence
之前,您需要为其分配内存。
patient_list->sequence = malloc(sizeof (seq) );
patient_list->sequence->begin = 10;
printf("%d",patient_list->sequence->begin);
如果您尝试从未指向有效内存的指针读取或写入,您将获得未定义的行为,异常 0xC0000005 是一个典型的结果。
请注意,seq
的 next
指针中仍然有一个未初始化的值,如果使用它同样是灾难性的。因此,您需要仔细构建数据序列,每个条目都被初始化并指向下一个条目。
您代码中的问题部分是您为 patient
结构分配了内存,但没有为 seq
结构中的 patient
结构分配内存。本质上,您为 sequence
指针分配了内存,但没有为其指向的位置分配内存。
这是一个简单的例子:
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。