【发布时间】:2020-06-19 17:44:31
【问题描述】:
我正在尝试创建一个节点的链接列表,这些节点内部都有一个员工结构指针。当我尝试将新节点添加到末尾时出现分段错误。下面是我将节点添加到列表末尾的函数。
void addToEnd(node_t **head, employee_t *employee){
node_t *current_node = *head;
while(current_node->next != NULL){
current_node = current_node->next;
}
current_node->next = (node_t*)malloc(sizeof(node_t));
current_node->next->empInfo = employee;
current_node->next->next = NULL;
}
这是我传递给函数的代码:
int main (void) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
employee_t *empPtr1, emp1,*empPtr2, emp2;
empPtr1 = &emp1;
empPtr2 = &emp2;
node_t head;
head.next = NULL:
node_t *headPtr;
node_t **headPtr2;
headPtr2 = &headPtr;
headPtr = &head;
emp1.firstName = (char *) malloc(sizeof(char)*10);
emp1.lastName = (char *) malloc(sizeof(char)*10);
emp2.firstName = (char *) malloc(sizeof(char)*10);
emp2.lastName = (char *) malloc(sizeof(char)*10);
printf("Please enter the first name of the first employee you'd like to add:");
scanf("%s", empPtr1->firstName);
printf("Please enter the last name of the first employee you'd like to add:");
scanf("%s", empPtr1->lastName);
printf("Please enter the first name of the second employee you'd like to add:");
scanf("%s", empPtr2->firstName);
printf("Please enter the last name of the second employee you'd like to add:");
scanf("%s", empPtr2->lastName);
addToEnd(headPtr2, empPtr1);
addToEnd(headPtr2, empPtr2);
...
如果有人知道为什么该函数给我一个段错误,那将不胜感激,因为我在这里查看了许多线程,没有发现任何类似的东西。
【问题讨论】:
-
哪个语句出现分段错误?
-
如果你的名字超过9个字符,你就会爆炸。考虑限制 scanf 输入以保护您。
-
了解
employee_t将有助于了解那里是否有问题。知道它在调试器中崩溃的那一行也会有很大帮助。此外,启用警告以查看编译器是否发现问题。
标签: c function linked-list segmentation-fault