0

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??

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;
    }
}
ajay
  • 9,402
  • 8
  • 44
  • 71
Bonzi
  • 33
  • 1
  • 3
  • 12

2 Answers2

0

Did you mean while loop instead if, and remove return statement.

Mikl X
  • 1,199
  • 11
  • 17
  • well, i tried using the while and removing the return statement, it still does nothing. – Bonzi Feb 23 '14 at 07:03
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

Community
  • 1
  • 1
Dabo
  • 2,371
  • 2
  • 18
  • 26