search a string in an array of strings

2019-07-29 05:48发布

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

标签: c ansi
4条回答
倾城 Initia
2楼-- · 2019-07-29 06:13

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.

查看更多
冷血范
3楼-- · 2019-07-29 06:25

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

Also, consider using strncmp().

查看更多
聊天终结者
4楼-- · 2019-07-29 06:25

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.

查看更多
我命由我不由天
5楼-- · 2019-07-29 06:30

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 ) { 
查看更多
登录 后发表回答