I’m fairly new to C programming but trying my best to understand it. I have two dynamic strings that are populated from two plain text files. One being a form of a dictionary, and the other one just a user input. What I want to get is binary search each user input word in the dictionary and find out if it is present (sort of a spell checker I guess).
I’m stuck on my binary search function:
char **dictElem;
int dictSize;
char **inputElem;
int binsearch(const char *val){
int pos;
int beg=0;
int end=dictSize-1;
int cond=0;
while (beg<=end){
pos=(beg+end)/2; //Jump in the middle
if ((cond=strcmp(dictElem[pos],val)) == 0)
return pos;
else if (cond<0)
beg=pos+1;
else
end=pos-1;
}
return 0;
}
Both dictElem and inputElem were already read by other methods and (let’s say) both [0] elements are equal strings "aa".
However after I run the binsearch(inputElem[0] it always returns 0. I tried just strcmp(dictElem[0],inputElem[0]) and it returns 1.
Where am I going wrong? Is it comparing char** and char*?
UPD:
Function that’s loading the dictElem
void readd(FILE *file){
int i=0,size=0; /* local size */
char line[1024]; /* Local array for a single word read */
printf("Loadingn dict...\n");
while ((fgets(line,sizeof(line),file))!=NULL){
dictElem=(char**)realloc(dictElem,(size+1)*sizeof(char *));
dictElem[size++]=strdup(line);
}
printf("Total elements loaded: %d\n",size);
}
Function that reads a user file is very similar, just a little different format.
The problem with your code is in this line
if ((cond=strcmp(dictElem[pos],val) == 0)). This line of code assigns the result of expressionstrcmp(dictElem[pos], val) == 0to the variablecond, and then checks whether cond is zero or not.I guess your original intent was to store in
condthe result ofstrcmp, so you should move the closing parenthesis before==. The correct line isif ((cond = strcmp(dictElem[pos], val) == 0).There are some other problems with your code:
returned when element is found at index 0.
char *val, whenit is better to use
const char *val, because contents of thisstring aren’t going to be modified. It is always better to write const-correct code.