The function I'm having trouble with is the insertAtIndex function, this function needs to insert a new customer data at the location indicated by the parameter "index". If index is 0 then it should be inserted as the first data in the linked list.
I can add one new element fine but when I try to add another the program crashes. Heres the code:
struct Contact
{
char * last_name;
char * first_name;
int id;
float balance;
struct Contact *next;
};
struct Contact * head = NULL;
int insertAtIndex(char * lastname, char * firstname, int id, float balance, int index)
{
int i;
struct Contact * newContact, *conductor;
conductor = head;
newContact = (struct Contact *) malloc(sizeof(struct Contact));
strcpy(newContact->last_name,lastname);
strcpy(newContact->first_name,firstname);
newContact->id = id;
newContact->balance = balance;
newContact->next = NULL;
if(conductor == NULL)
{
head=newContact;
newContact->next = NULL;
}
else
{
for(i = 0; i< index; i++)
{
conductor=conductor->next;
}
conductor->next=newContact;
}
return index;
}
Heres two more functions that is supposed to do the same thing as the one above but has the same problem:
int insertAtIndex(char * lastname, char * firstname, int id, float balance, int index)
{
int i;
struct Contact * newContact, *conductor;
conductor = head;
newContact = (struct Contact *) malloc(sizeof(struct Contact));
lastname = (char *)malloc(50 * sizeof(char));
firstname = (char *)malloc(50 * sizeof(char));
strcpy(newContact->last_name,lastname);
strcpy(newContact->first_name,firstname);
newContact->id = id;
newContact->balance = balance;
newContact->next = NULL;
if(conductor == NULL)
{
head=newContact;
newContact->next = NULL;
}
else
{
for( i = 0; conductor && i < index; i++, conductor = conductor->next )
{
if( conductor->next == NULL )
break;
}
newContact->next = conductor->next;
conductor->next = newContact;
}
return index;
}
and
int insertAtIndex(char * lastname, char * firstname, int id, float balance, int index)
{
struct Contact *temp,*r;
int i;
temp=head;
r=(struct Contact*)malloc(sizeof(struct Contact));
lastname = (char *)malloc(50 * sizeof(char));
firstname = (char *)malloc(50 * sizeof(char));
strcpy(r->last_name,lastname);
strcpy(r->first_name,firstname);
r->id = id;
r->balance = balance;
if(head == NULL)
{
head=r;
r->next = NULL;
}
else
{
for(i=0;i<index;i++)
temp=temp->next;
if(temp==NULL)
{
printf("there are less than %d elements in list\n",index);
return -1;
}
r->next=temp->next;
temp->next=r;
}
return index;
}
I'm not sure what I'm doing wrong.
I can post my whole code with the main function if need to be. Any help would be appreciated.
Edited by Mt570, 26 September 2009 - 07:33 PM.


Sign In
Create Account

Back to top










