如何解决如何为不同的char指针分配malloc
我有一个这样的结构
struct Patient {
char* name;
char* address;
char* socialSecurityNumber;
char* typeOfExamination;
bool isExpress;
}
我必须从这样的txt文件中填充此结构的动态数组: (定界符:“;”)
Andrew;Address street first;123;pulmonary;1
Matthew;Address street second;456;COVID;0
Lisa;Address street third;789;rectum;0
打开文件并读取文件后:
while (fgets(line,255,(FILE*) fPtr)) {
char *p = strtok (line,";");
patients[i].name=(char*)malloc(sizeof(char*));
strcpy(patients[i].name,p);
p = strtok (NULL,";");
patients[i].address=(char*)malloc(sizeof(char*));
strcpy(patients[i].address,p);
...
i++;
}
第二个malloc / strcpy之后,我得到一个sysmalloc:断言失败错误
我在做什么错了?
解决方法
patients[i].name=(char*)malloc(sizeof(char*));
为单个字符指针分配足够的空间,大约4到8个字节。您需要为每个字符分配足够的空间,并在末尾添加一个空字节。
patients[i].name = (char*)malloc(sizeof(char) * (strlen(p)+1));
那可以,但是我们可以减少它。 There's no need to cast malloc
。通常,我们也将长度乘以sizeof
类型,但是sizeof(char)
始终为1,因此可以省略。
patients[i].name = malloc(strlen(p)+1);
您可以使用strdup
执行相同的操作,但这不是POSIX函数始终可用的功能。经常写自己的书是值得的。
patients[i].name = strdup(p);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。