Search code examples
cansi-c

search a string in an array of strings


I keep getting bad pointers. Can anyone tell me what am I doing wrong?

int SearchString( char* arr[], char* key, int size )
{
int n;
for ( n = 0; n < size; ++n ) {
    if ( strcmp(arr[n], key) ) { 
        return n;
    } 
} 
return -1;

}

char str[][16] = { "mov","cmp","add","sub","lea","not","clr","inc","dec","jmp","bne","red","jrn","psr","rts","stop"};

    if(SearchString(str,"word",16) == -1){  return FALSE;}

Solution

  • Can't tell where your word originates from. You probably want to if (!strcmp(arr[n],key)) return n; (the reverse). And the type of array is probably not what you want. Try

    const char *str[] = { "mov",.... };
    

    instead. You have an array of arrays of characters and pass it where you actually expect an array of pointers.