gpt4 book ai didi

c - 使用结构打印链接列表

转载 作者:行者123 更新时间:2023-11-30 19:02:23 26 4
gpt4 key购买 nike

我收到了一项家庭作业,需要填写所有函数。现在,当我进入第三次打印时,我收到一个错误,指出 ptr(变量)无法访问数据(在他可以之前?)

我尝试在将值发送到函数之前打印这些值,看看它得到了什么,它得到了正确的名称,但函数中的某些东西搞砸了

结构:

typedef struct {
char name[32];
char surname[32];
char id[32];
char position[64];
int salary;
} EmployeeData;

typedef struct tEmployeeNode {
EmployeeData data;
struct tEmployeeNode *next;
} EmployeeNode;

包含所有数据的数组:

    EmployeeData data[4] = {
{ "John","Silver","200011123", "Mutineer", 3000 },
{ "David","Livesey","122233345", "Doctor", 7000 },
{ "Jim","Hawkins","201072716", "Cabin Boy", 1000 },
{ "John","Trelawney","122233444", "Squire", 200 } };

创建节点

EmployeeNode *createEmployeeNode(EmployeeData data) {
EmployeeNode *temp = (EmployeeNode *)malloc(sizeof(EmployeeData));
temp->data = data;
temp->next = NULL;
return temp;
}

创建链表函数

EmployeeNode *createListOfEmployees(EmployeeData *arr, int size) {
int i;
EmployeeNode *head, *ptr;
EmployeeNode *temp = (EmployeeNode *)malloc(sizeof(EmployeeData));
if (temp == NULL) {
printf("Error\n");
exit(1);
}
temp->data = arr[0];
temp->next = NULL;
head = temp;
ptr = head;
for (i =1; i < size; i++) {
temp = createEmployeeNode(arr[i]);
if (ptr->next != NULL) {
ptr = ptr->next;
}
else {
ptr->next = temp;
temp->next = NULL;
}
}
return head;
}

主要 printf 函数:

void printListOfEmployees(EmployeeNode *head) {
EmployeeNode *ptr = head;
while (ptr != NULL) {
printEmployee(ptr->data);
ptr = ptr->next;
}
}

printf 函数内部:

void printEmployee(EmployeeData e) {
printf("%s %s %s %s %d\n", e.name, e.surname, e.id, e.position, e.salary);
}

这是我实际调用函数的地方

    EmployeeNode *head = createListOfEmployees(data, 4);
printf("Employees of the Espaniola Team:\n\n");
printListOfEmployees(head);

结果应该是:A。所有数组节点都应该位于具有到下一个节点的链接列表的结构中,并按正确的顺序打印所有内容。我的主要问题是我失去了“Jim Hawkins”并且不明白为什么。

感谢您的帮助!

最佳答案

createListOfEmployees 的正确正文函数(为简洁起见,没有错误检查):

EmployeeNode *head= NULL;
EmployeeNode *previousnode = NULL;

for (int i = 0; i < size; i++) {
EmployeeNode *newnode = createEmployeeNode(arr[i]);
if (previousnode != NULL)
previousnode->next = newnode;
else
head = newnode;

previousnode = newnode;
}

return head;

保持简单。

关于c - 使用结构打印链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56018471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com