当我运行这些方法时,我的列表永远不会增长,我不知道为什么。头部和尾部总是相等的。我的指针或结构设置有问题吗?我花了4个小时来切换这些东西,我似乎无法找到为什么事情不起作用,除非它是指针的东西(我正在学习并且不擅长)...
typedef struct EmployeeStruct
{
char LastName[10];
char FirstName[10];
struct EmployeeStruct *next;
} Employee;
struct EmployeeStruct *head,*tail, *temp;
Employee* hireEmployee(Employee* head, char LastName[10], char FirstName[10])
{
// exit if max number of employees is reached
if(eNum > MAX_EMPLOYEES)
{
printf("Sorry, but you can't hire any more employees right now\n");
return 0;
}
// insert at tail
newHire = head;
while(newHire->next != NULL)
{
newHire = newHire->next;
printf("nope\n");
}
// allocate memory
newHire->next = malloc(sizeof(Employee));
if(newHire == NULL)
{
printf("Memory allocation failed");
return 0;
}
newHire->next = NULL;
// insert values into this node
strcpy(newHire->LastName, LastName );
strcpy(newHire->FirstName, FirstName );
newHire->EmployeeNumber = eNum;
tail = newHire;
//printf("%d\n",newHire->EmployeeNumber);
eNum+=1;
//printf("%d\n",newHire->EmployeeNumber);
return newHire;
}
int main()
{
char choice;
char first[20];
char last[20];
int i = 0;
// allocate memory
head = malloc(sizeof(Employee));
if(head == NULL)
{
printf("Memory allocation failed");
return 0;
}
head->next = tail;
while(TRUE)
{
// prompt user for choice
printf("Please choose from the following options:\n");
printf("a: Hire new employee\nb: Promote employee\nc: Delete employee\nd: Display roster\ne: Exit\n");
scanf("\n%c", &choice);
switch(choice)
{
case 'a':
printf("New employees first name:\n");
scanf("%s", first);
printf("New employees last name:\n");
scanf("%s", last);
tail = hireEmployee(head,last,first);
temp = head;
while(temp->next != NULL)
{
temp = temp->next;
printf("nope\n");
}
temp->next = tail;
tail = temp->next;
printf("A%d: %s %s\n", tail->EmployeeNumber,tail->FirstName,tail->LastName);
tail = tail->next;
printf("A%d: %s %s\n", tail->EmployeeNumber,tail->FirstName,tail->LastName);
tail->next = NULL;
//printEmployees(head);
break;
case 'b':
//TBD
break;
}
}
}
**现在可以使用,就是这四个错误:
(newHire == NULL)
(head == NULL)
newHire =newHire->next;
temp->next = tail;
顺便说一下,我总是做作业并上课,而我只是停留在一个较大的程序中。所以,谢谢那些没有侮辱我并实际提供有用建议的人。我真的很感激。
答案 0 :(得分:2)
这是你的错误
newHire->next = malloc(sizeof(Employee));
malloc的返回类型为void *因此将其更改为
newHire->next = (EmployeeStruct *)malloc(sizeof(Employee));
if(newHire == NULL)
永远不会将NULL更改为
if(newHire->next == NULL)
也改变了
newHire->next = NULL;
你必须再遍历一次链接
newHire=newHire->next;
newHire->next = NULL;
答案 1 :(得分:1)
我认为问题出在这里
temp->next = tail;
tail = temp->next;
在case 'b'
因为它将temp->next
设为head