search a string in an array of strings

心不动则不痛 提交于 2019-12-11 07:54:09

问题


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;}

回答1:


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.




回答2:


Change char str[][16] to char *str[16] (or only char *str[]).

Also, strcmp returns zero when the strings are equal, so you want this instead:

if ( strcmp(arr[n], key) == 0 ) { 



回答3:


strcmp() returns zero if strings are equal! Your test should be if (!strcmp(...))

Also, consider using strncmp().




回答4:


The parameter is passed as char **ar which is not correct.

One of the alternatives is changing protopype to:

int SearchString( char arr[][16], char* key, int size ) to get the expected behaviour.



来源:https://stackoverflow.com/questions/8848940/search-a-string-in-an-array-of-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!