Okay, I tried the strcpy function and I tried sprintf. They both compiled with no errors, but then I had a runtime error. I think I tracked the error down to the functions strcpy (the first time) and sprintf (the second time). Here is the code. Tell me if you find the error.
Code:
/**************************************************
**** A cross-reference program illustrating ****
**** the use of linked lists ****
***************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NAMESIZE 50
struct list {
char name[NAMESIZE]; /* Holds the name of reference */
struct list *next_list; /* The next reference to name */
};
/***************************************************
* fndnm - searches through the linked list to
* find the given name
*
* parameters - pointer to first struct and name
*
* return - 0 if null, 1 if found
****************************************************/
int fndnm(struct list *first_list, char *search)
{
struct list *look_list;
/* start with the first struct */
look_list = first_list;
while (1)
{
if (look_list == NULL)
return 0;
else if (look_list->name == search)
return 1;
else
look_list = look_list->next_list;
}
}
int main()
{
int counter, yesno;
struct list *init_list;
char line[100];
for (counter = 0; counter < 5; ++counter)
{
printf("Enter a name: ");
fgets(line, sizeof(line), stdin);
line[strlen(line)-1] = '\0';
sprintf(init_list->name, "%s", line);
/* goto next list */
init_list = init_list->next_list;
}
printf("Now, enter a name to search: ");
fgets(line, sizeof(line), stdin);
line[strlen(line)-1] = '\0';
yesno = fndnm(init_list, line);
if (yesno)
printf("Found = TRUE");
else
printf("Found = FALSE");
return (0);
}
This is it. The first time I tried, I replaced sprintf(init_list->name, "%s", line) with strcpy(init_list->name, line). Thanks.