for the following code when I search for top hat I am not getting the desired result(i.e found) Instead the output is not found. I assume it is to do with how the char arrays are working behind the scenes, can anyone explain this to me.
#include <string.h>
#define MAX_LIMIT 20
int main(void)
{
char strin[MAX_LIMIT];
char numbers[6][10] = {"battleship","boat","cannon","iron","thimble","top hat"};
printf("enter string to search:");
scanf("%s", &strin);
for(int i=0;i<6;i++)
{
if(strcmp(numbers[i],strin)==0)
{
printf("found\n");
return 0;
}
}
printf("not found\n");
return 1;
}
scanfinscanf("%s", &strin);will read data from stdin until a whitespace character occurs.As such, when you type into "top hat",
scanfwill readtopnottop hat.I ran your code,value of
strinwastop. There is not such string in numbers.strinis an array of char.The name of an char array is memory address.I think usingstrininstead of&strinis better.If I want to search "top hat" in numbers,I will use
fgetsinstead ofscanf.Here is my code.It works well.