问题描述
我正在尝试编写一个包含“Person”结构的双向链表,但我的主程序在“Get”函数期间崩溃以从列表中返回一个 Person
这是列表程序:
链表.c (注意,我正在削减一些东西,包括我释放 malloc 的地方,但我包括 CreateList() 和 insertAt(),因为它们是 main.c 中 Get() 之前使用的唯一部分)
#include <stdlib.h>
#include <stdio.h>
#include "person.h"
#include "linkedlist.h"
List CreateList(){
List list = malloc(sizeof(struct list));
list->size = 0;
list->first = NULL;
list->last = NULL;
return list;
}
...
void insertAt(List list,Person person,int pos) {
Node link = malloc(sizeof(Node));
if (link == NULL){
printf("Malloc Failed\n");
return;
}
link->data = &person;
link->next = NULL;
link->prevIoUs = NULL;
Node* current = list->first;
if (pos > list->size || pos < 0){
printf("Error - Invalid position\n");
return;
}
if (pos > list->size || pos < 0){
printf("Error - Invalid position\n");
return;
}
if(list->size == 0){
list->first = &link;
list->size++;
return;
}
if(pos == 0){
link->next = *list->first;
list->first = &link;
list->size++;
return;
}
if(pos == list->size){
link->prevIoUs = *list->last;
list->last = &link;
list->size++;
return;
}
for (int i = 0; i < pos; i++){
current = &(*current)->next;
}
link->next = (*current)->next;
link->next->prevIoUs = link;
link->prevIoUs = (*current)->prevIoUs;
link->prevIoUs->next = link;
return;
}
...
Person Get(List list,int pos){
Person bob;
Node* current = list->first;
if (pos >= list->size || pos < 0){
printf("Error - Invalid position");
return bob;
}
if (IsEmpty(list)){
printf("Error - List is empty");
return bob;
}
for (int i = 0; i < pos; i++){
current = &(*current)->next;
}
Person* bobPtr = (*current)->data;
bob = (Person) *bobPtr; // segfault happens here
return bob;
}
这是我的头文件:
链接列表.h
#ifndef LIST_H
#define LIST_H
#include "person.h"
typedef struct node {
Person* data;
struct node* prevIoUs;
struct node* next;
} *Node;
typedef struct list {
Node* first;
Node* last;
int size;
} *List;
List CreateList();
void DestroyList(List*);
void CleanList(List);
void InsertFirst(List,Person);
void InsertLast(List,Person);
void insertAt(List,Person,int);
Person RemoveFirst(List);
Person RemoveLast(List);
Person RemoveAt(List,int);
Person First(List);
Person Last(List);
Person Get(List,int);
int IsEmpty(List);
int IsFull(List);
int Size(List);
# endif
person.h
#ifndef PERSON_H
#define PERSON_H
typedef struct person{
int id;
char name[20];
int age;
} Person;
#endif
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)