我是一个初学者,试图将信息添加到/更新信息中包含在另一个链接列表中的链接列表中。我的程序是一个简单的联系人列表,其中用户可以将联系人添加到列表中,然后将信息添加到每个联系人(使用单独的信息列表)中。我的附加信息功能会遇到细分错误,而且我看不到问题是什么。以下是结构的定义:
typedef struct info {
char *name;
char *value;
struct info *next;
} Info;
typedef struct contact {
char *name;
Info *information;
struct contact *next;
} Contact;
这是我的添加信息功能:
void addInformation(Contact *myContacts, char *contactName, char *infoName, char *infoValue) {
Contact *ptr = myContacts;
Info *ptr2 = ptr->information;
if (ptr == NULL) {
printf("Error: No contacts added.n");
return;
}
while (ptr != NULL) {
if (ptr->name != contactName) {
printf("Error: Contact does not existn");
return;
}
else {
ptr2->name = infoName;
ptr2->value = infoValue;
ptr2->next = NULL;
ptr->information = ptr2;
}
ptr = ptr->next;
}
return;
}
如果有人可以告诉我我在代码中做错了什么,那将不胜感激!谢谢。
我的第一个反应是,没有分配联系 ->信息的内存。因此,ptr2为空或垃圾。@yano已经提到了。
我试图在原始代码上写评论,然后决定用一些注释编写新版本会更清楚。将代码分为几个函数会更好。
void addInformation(Contact *myContacts, char *contactName, char *infoName, char *infoValue) {
Contact *ptr = myContacts;
if (ptr == NULL) {
printf("Error: bad pointer to contacts storage.n");
return;
}
while (ptr != NULL) {
if (strcmp(ptr->name,contactName) == 0) {
// if it's a contact with the name we are looking for
// then allocate and put info structure as a head of the list of info
Info *newInfo = malloc(sizeof(Info));
newInfo->name = infoName;
newInfo->value = infoValue;
newInfo->next = ptr->information;
ptr->information = newInfo;
return; // get out as we found our contact
} else if (ptr->next == NULL ) {
// there is nothing next, we are at the end of the list
// allocate memory for both contact and information, fill it in
// add the contact as the last element in the list of contacts.
Contact* newContact = malloc(sizeof(Contact));
newContact->name = contactName;
newContact->information = malloc(sizeof(Info));
newContact->information->name = infoName;
newContact->information->value = infoValue;
newContact->information->next = NULL;
newContact->next = NULL;
ptr->next = newContact;
return; // get out as there is no reason to iterate more, it's the last element in the list
} else {
ptr = ptr->next;
}
}
return;
}
int main(int argc, const char * argv[]) {
// Has to allocate the first contact. Otherwise the pointer management
// will have to be different and addInformation function has to accept
// pointer to pointer.
Info info = { "nn", "vv", NULL };
Contact myContacts = { "contact 1", &info, NULL };
addInformation(&myContacts, "contact 2", "info 1", "val 2");
addInformation(&myContacts, "contact 2", "info 3", "val 4");
addInformation(&myContacts, "contact 1", "info 5", "val 6");
printf("end");
return 0;
}