I have simple string comparison routine. Recently added string keyboard input, but something is wrong. Function "cmp("ala", dict);" works just fine. I suspect zero-termination issue related to strings in general, or some buffer length incompatibility.
Search input "ala" returns no hit. But (after commenting unnecessary code) this is ok "cmp("ala", dict);"
This is the code.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *MyText[256];
char **dictionary()
{
char **dict = (char**)malloc(sizeof(char*) * 5);
int i = 0;
for(i = 0; i < 5; i++)
dict[i] = (char*)malloc(sizeof(char) * 7);
strcpy(dict[0], "mark");
strcpy(dict[1], "ala");
strcpy(dict[2], "wojtek");
strcpy(dict[3], "tom");
strcpy(dict[4], "john");
return (dict);
}
void free_dictionary(char **dict)
{
for (int i = 0; i < 5; i++)
free(dict[i]);
free(dict);
}
int cmp(char *s1, char *s2[5])
{
int i = 0;
int n = 0;
for (i = 0; i < 5; i++)
if (strcmp(s1, s2[i]) == 0) {
n++;
}
if (n > 0)
printf("Found %d", n);
else
printf("Nothing found");
}
int main(int argc, char *argv[])
{
char BufText[255];
int n=0;
char sign;
fflush(stdin);
printf("Give me names: \n");
n = 0;
do {
sign = getchar();
BufText[n ++] = sign;
if(n >= 253) break;
} while (sign !='\n');
BufText [n] = 0;
char **dict = dictionary();
cmp(BufText, dict);
free_dictionary(dict);
return 0;
}