在字符串数组中搜索字符串

发布于 2024-12-26 16:06:26 字数 438 浏览 2 评论 0原文

我不断收到不好的指点。谁能告诉我我做错了什么?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

红颜悴 2025-01-02 16:06:26

无法判断您的单词源自何处。您可能想要 if (!strcmp(arr[n],key)) return n; (相反)。并且数组的类型可能不是您想要的。尝试

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

一下。您有一个字符数组数组,并将其传递到您实际需要指针数组的位置。

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.

梦里泪两行 2025-01-02 16:06:26

char str[][16] 更改为 char *str[16](或仅 char *str[])。

另外,当字符串相等时,strcmp 返回零,因此您需要这样:

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

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 ) { 
人│生佛魔见 2025-01-02 16:06:26

如果字符串相等,strcmp() 返回!您的测试应该是 if (!strcmp(...))

另外,请考虑使用 strncmp()

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

Also, consider using strncmp().

陌上青苔 2025-01-02 16:06:26

该参数作为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文