This is an address:
struct Adress {
char name[31], lastname[31], email[48];
};
The goal is to have an address book in the main function, and the user should be able to type in a string, and the program lists out all of the people from the address book whose name or the last name contains the given string. For example, if the address book contains "john" "doe", "jane" "doey" and "george" "johnson", and the user types in "doe", the output is:
1. john doe [email protected]
2. jane doey [email protected]
This part of the main function should use a function
int search(struct Adress array[], int size_of_the_addressbook, char* string_to_search)
which returns the index of the first found address, and -1 in case no address has been found.
Here's my try:
In the snippet from my main function (there 's no need to post input stuff here):
struct Adress adressbook[1000], *member;
int i = 0;
member = adressbook;
if (search(member, number_of_elements, string_to_seach)) == -1)
printf("No person found.\n");
else while((search(member, number_of_elements, string_to_seach)) != -1)
{
member = adressbook + search(member, number_of_elements, string_to_seach);
++i;
printf("%d. %s %s - %s\n", i, (*member).name, (*member).lastname, (*member).email);
++member;
}
And here's the search function:
int search(struct Adress array[], int size_of_the_addressbook, char* string_to_search)
{
int j, index;
struct Adress *i;
i = array;
while (strstr((*i).name, string_to_search) == 0 && strstr((*i).lastname, string_to_search) == 0)
{
index = ((i - array)/(sizeof (struct Adress)));
if (index == size_of_the_addressbook) return -1;
++i;
}
index = ((i - array)/(sizeof (struct Adresa)));
return index;
}
However, this program gets stuck in an infinite loop in pretty much any case when there is more than one member in the address book. I'm suspecting that in the while loop the search doesn't go on from the previously found member, but rather it starts from the begin each time, therefore it keeps finding the same, firstly found member each time.
indexinsearch. Pointer math will do that for you.index = (i - array);should be sufficient to get the correct index.iwhich iterates from0to the length of the array and reference,array[i].name, etc? As far as the infinite loop, how issize_of_the_addressbookcomputed before being passed to the function?int ifrom0tonumber_of_elements-1referencingarray[i]. It would be much cleaner, and your loop would at least properly terminate, leaving you to address other issues.