holycatcrusher holycatcrusher - 1 day ago 3
C Question

Problems comparing a string to an array of strings C

I am about to have a stroke, I cannot figure why this code doesn't work. The goal is to search an array of strings for a string. If the string being searched for is found, the method returns true, and if not, false. Unfortunately I've made some sort of error, and am about to have a stroke, because I cannot figure out what it is. The printf is just there to show that the array is being iterated through, your help is much appreciated. Also, the -1 in the for loop is just something that helps, I don't think it should be there, but watch what happens when you take it out. Also, I'd like to point out that that the way I declared the array is the way I need to, because of the section I am currently studying.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool seachForString(char *firstString, int numberOfStrings, char *searchingFor);

int main(void){

bool found;
char *search = "Earth";

char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
found = seachForString(planets[0], 9, search);

printf("Found: %d\n", found);

return 0;
}

bool seachForString(char *firstString, int numberOfStrings, char *searchingFor){
char *stringInList = firstString;

for(int i=0; i<numberOfStrings-1; i++){
printf("%s\n", stringInList);
if(strcmp(stringInList, searchingFor) == 0){
return true;

}else{
while(*(stringInList++) != '\0');

}

}

return false;
}

Answer

If you set char *search = "Earth"; after char *planets[] = {...};, it may work.
E.g.

char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
char *search = "Earth";

However, placement of string literals is not always what you want. There is no such guarantee.

So change it to pass the array.

like this:

bool seachForString(char *firstString[], int numberOfStrings, char *searchingFor);

int main(void){

  bool found;
  char *search = "Earth";

  char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
  found = seachForString(planets, 9, search);

  printf("Found: %d\n", found);

  return 0;
}

bool seachForString(char *firstString[], int numberOfStrings, char *searchingFor){
  char **stringInList = firstString;

  for(int i=0; i<numberOfStrings; i++){
    printf("%s\n", *stringInList);
    if(strcmp(*stringInList++, searchingFor) == 0)
      return true;
  }

  return false;
}
Comments