Alright i'm trying to write a program that checks a list of names entered by the user to see if the new name entered is part of the list. If it's not part of the list it should return -1 to the main, and print no names found, if it is part of the list, it should return 0 and print the position of the name.

My issue that I'm having is I'll type a list of names, and then type a name to search, and unless that name is the first name on the list, it says name not found. Also, if you look at the code you'll notice that I'm printing "name found" rather then the string postion, and thats simply because I haven't figured out how to do that yet lol :). Help with this delemma would be greatly appreciated.


#define MAX_NAMES 5
void initialize(char names[MAX_NAMES][MAX_NAMELENGTH]);
int search(char names[MAX_NAMES][MAX_NAMELENGTH],int i, int Number_entrys);
int main()

    char names[MAX_NAMES][MAX_NAMELENGTH];
    int i, Number_entrys,search_result,x;
     search_result= search(names,i,Number_entrys);
     if (search_result==-1){
        printf("Found no names.\n");
     printf("Name found");
    return 0;

void initialize(char names[MAX_NAMES][MAX_NAMELENGTH])
     int i,Number_entrys;

     printf("How many names would you like to enter to the list?\n");

                   printf("Please choose a smaller entry\n");
      for (i=0; i<Number_entrys;i++){


int search(char names[MAX_NAMES][MAX_NAMELENGTH],int i,int Number_entrys)
    int j,n,x;
    char new_name[MAX_NAMELENGTH];
    printf("Now enter a name in which you would like to search the list for\n");


for(x = 0; x < Number_entrys; x++) {
    if ( strcmp( new_name, names[x] ) == 0 ){

        return x;
          return -1;   

Recommended Answers

All 2 Replies

On line 62 and 64, you are returning prematurely - after the first name search fails.

You need to put those returns at the very bottom of the function. To return more data from the function you need to send in another parameter, a pointer, so the variable it holds the address of, can be modified, and available in the calling function.

You could also put it into a struct, but I won't advise it.

The problem is related to the if/else block in your search function's for() loop. The if statement is executed each iteration, so if we find a match... great! Return x! But note that if the if fails, then the else is executed and -1 is returned. Thus you are only able to test the first value. Try removing the else and moving the return -1 outside the for loop. If the name is found then you'll be fine (since 'x' will be returned). If the value isn't found (we get to the end of the loop) then -1 is returned as it should be. Hope this helps!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.