Showing posts with label Why below code's output is “not found” instead of “found”?. Show all posts
Showing posts with label Why below code's output is “not found” instead of “found”?. Show all posts

Sunday, October 6, 2013

Why below code's output is “not found” instead of “found”?

below code gives “Not found” output. But I expect it to donate “found”. Where is my mistake?

#include <stdio.h>void compare(char *x, char *face);int i;int main(void){char array[5]="Two";char *numbers[4]={"One", "Two", "Three", "Four"};compare(array, *numbers);}void compare(char *x, char *y){for (i = 0; i < 4; i++){    if (*x==y[i])    {        printf("\n found");        return;    }}printf("\n not found\n");}

In *x==y[i] you are comparing the value of two chars instead of the data pointed to by two pointers. Use the strcmp function instead. It returns 0 if the two strings pointed to by the given two pointers are equal. So alter it to strcmp(x, y[i]) == 0

Also you should alter the char *y parameter to char **y or char *y[] because y is an array of pointers to strings, not just one pointer.

Finally, compare(array, *numbers); should be called as compare(array, numbers); because you want to pass a pointer to the array of strings, not just a pointer to one string (numbers is of type char*[4] yet it will decay to type char** when passed as an argument).