This code is for adding an employee profile at the beginning of a linked list. For some reason, which i cannot identify, this code worked once, and then it just printed the printf and then exited the loop. Even after entering numerous records, it was still doing the same thing. So can anyone identify the problem??
此代码用于在链接列表的开头添加员工配置文件。由于某种原因,我无法识别,这段代码工作了一次,然后它只打印了printf然后退出循环。即使在输入了大量记录之后,它仍然在做同样的事情。所以任何人都能找出问题吗?
void insert_tobeg() {
char name[15];
struct employee *newPtr;
printf("\n\n\tEnter the record to be entered:");
gets(name);
if(strcmp(start->name, name) == 0) {
curr = (struct employee*)malloc(sizeof(struct employee));
employee_entry();
curr->newPtr = start;
start = curr;
printf("\n\n\tRecord has been added at the beggining!");
return;
}
}
2 个解决方案
#1
0
You manage it incorrect, you overwrite the name in first element, you need to write to the currently allocated ellement. Try something like this
您管理它不正确,您在第一个元素中覆盖名称,您需要写入当前分配的元素。尝试这样的事情
curr = (struct employee*)malloc( sizeof(struct employee));
employee_entry();
if( strcmp( curr->name, name) == 0)
{
curr->newPtr=start;
start = curr;
printf("\n\n\tRecord has been added at the beggining!");
return;
}
else
{
free(curr);
}
And don't cast malloc result in C
并且不要在C中强制转换malloc结果
#2
0
Did you mean while loop instead if, and remove return statement.
你的意思是while而不是if,并删除return语句。
#1
0
You manage it incorrect, you overwrite the name in first element, you need to write to the currently allocated ellement. Try something like this
您管理它不正确,您在第一个元素中覆盖名称,您需要写入当前分配的元素。尝试这样的事情
curr = (struct employee*)malloc( sizeof(struct employee));
employee_entry();
if( strcmp( curr->name, name) == 0)
{
curr->newPtr=start;
start = curr;
printf("\n\n\tRecord has been added at the beggining!");
return;
}
else
{
free(curr);
}
And don't cast malloc result in C
并且不要在C中强制转换malloc结果
#2
0
Did you mean while loop instead if, and remove return statement.
你的意思是while而不是if,并删除return语句。