在字符串数组中搜索字符串
我不断收到不好的指点。谁能告诉我我做错了什么?
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;}
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;}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无法判断您的
单词
源自何处。您可能想要if (!strcmp(arr[n],key)) return n;
(相反)。并且数组的类型可能不是您想要的。尝试一下。您有一个字符数组数组,并将其传递到您实际需要指针数组的位置。
Can't tell where your
word
originates from. You probably want toif (!strcmp(arr[n],key)) return n;
(the reverse). And the type of array is probably not what you want. Tryinstead. You have an array of arrays of characters and pass it where you actually expect an array of pointers.
将
char str[][16]
更改为char *str[16]
(或仅char *str[]
)。另外,当字符串相等时,
strcmp
返回零,因此您需要这样:Change
char str[][16]
tochar *str[16]
(or onlychar *str[]
).Also,
strcmp
returns zero when the strings are equal, so you want this instead:如果字符串相等,
strcmp()
返回零!您的测试应该是if (!strcmp(...))
另外,请考虑使用
strncmp()
。strcmp()
returns zero if strings are equal! Your test should beif (!strcmp(...))
Also, consider using
strncmp()
.该参数作为 char **ar 传递,这是不正确的。
其中一种替代方法是将原型更改为:
int SearchString( char arr[][16], char* key, int size )
以获得预期的行为。
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.