【问题标题】:Function to search for string in array of strings在字符串数组中搜索字符串的函数
【发布时间】:2015-04-22 16:48:26
【问题描述】:

我正在尝试编写一个函数,用于在字符串数组中搜索字符串的唯一部分(最多两个字符)。尽管strstrstrchr 无法正常工作并且由于某种原因使我的程序崩溃。所以我求助于尝试创建类似于它们的功能的东西。

我的问题是:
为什么 strstr 不起作用(类似于 strstr(lex[j],word)),我在这里做错了什么?

这是在字符串数组中搜索两个唯一字符的函数的代码:

void convert(char word[])
{
    int i;

    for (i = 0 ; i <= strlen(word) ; i++)
    {
        if(word[i] >= 65 && word[i] <= 90)
        {
            word[i] = word[i]+32;
        }
    }
}


int  twochar(char lex[50][50],char word[], int size,char temp[3])
{
    int i,j,k,count,totlen;
    convert(word);

    for (i = 0 ; i < strlen(word) - 1 ; i++)
    {
        count = 0;
        totlen = 0;
        for(j = 0; j<size; j++)
        {
            convert(lex[j]);
            totlen += strlen(lex[j]) - 1;
            for(k = 0 ; k < strlen(lex[j]) - 1 ; k++)
            {
                if (word[i] != lex[j][k] || word[i+1] != lex[j][k + 1])
                {
                    count++;
                }
            }
        }
        if(count =  = totlen)
        {
            temp[0] = word[i];
            temp[1] = word[i+1];
        }
    }
}



int main(int argc, char *argv[])
{
    char lex[50][50] =  {"word1","word2","word3","word4" }, word[] = "test";
    char p[3];

    twochar(lex,word,4,p);
    printf("%c%c\n",p[0],p[1]);
    return 0;
}

【问题讨论】:

  • 这个strlen(lex[j])-1 是灾难的收据。想象一下如果lex[j] 是一个长度为0 的空“字符串”会发生什么。提示:检查 strlen() 返回的类型。
  • 我删除了我的评论,其中说您不会使用 temp[2]='\0' 终止 temp[],因为我注意到您从不使用 tempp 作为字符串,仅作为普通数组使用。
  • 我知道这不是最好的解决方案,但有什么替代方案?
  • 在调试器中运行您的代码,跟踪它并检查相关值。要了解如何执行此操作,您可以阅读此处:ericlippert.com/2014/03/05/how-to-debug-small-programs
  • 在这种情况下,代码会更清晰if(word[i] &gt;= 'A' &amp;&amp; word[i] &lt;= 'Z')

标签: c arrays string function


【解决方案1】:

这一行:

for(k=0;k<strlen(lex[j])-1;k++)

是问题所在。

strlen(lex[0]) is 0
strlen(lex[0])-1 is -1 (0xFFFFFFFF in a 32 bit system)
k starts at 0 and is incremented until it is equal to 0xFFFFFFFF

当然,当 k = 50 时,k 超出了 lex[0] 的范围。

结果是导致段错误事件的未定义行为

为了确定以上所有内容,我通过 gcc 使用 -ggdb 参数编译/链接了程序。

然后我通过“gdb theprogram”运行程序

within gdb I entered
br main <-- break point set
run
c <-- continue
the program then crashed with a seg fault event
then I entered
bt  <-- back trace
the bt showed me this line: 'if(word[i]!=lex[j][k] || word[i+1]!=lex[j] [k+1])'
Then I entered
p k <-- print variable k
=6832   (which is WAY out of bounds)

then I entered
run
y
br theprogram.c:41    (the line number from above) <-- set another break epoint
c
the program stopped at line 41
p j
=0  ( this was the gdb response )
p k 
= 0
p i
= 0

a little thinking, 
stepping though that inner loop using 'n' <-- next
and playing on gdb 
indicated that the problem was in line 42
and resulted in revealing the root of the problem

【讨论】:

  • 顺便说一句:编译器警告可以通过将某些循环变量声明为“size_t”而不是“int”来消除
猜你喜欢
  • 2011-07-04
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2013-04-11
  • 2013-01-09
相关资源
最近更新 更多