打印链接列表时出现结构错误

时间:2019-05-07 08:28:27

标签: c

我有一个家庭作业,需要填写所有功能。 现在,当我进入第三张打印纸时,我收到一个错误,即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);

结果应为: 一种。所有数组节点都应在Struct中,并带有指向下一个节点的链接列表,并按正确的顺序打印所有内容。 主要是我的问题是我输了“吉姆·霍金斯”,无法弄清楚原因。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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;

保持简单。