2

strcmp 関数を実装するためにこの割り当てを行いました。正常に動作することもありますが、クラッシュすることもあります。私を助けてください。

#include <iostream>

using namespace std;     

int mystrcmp(const char *s1, const char *s2);

int main()
{
cout<<mystrcmp("A","A")<<endl;     
cout<<mystrcmp("B","A")<<endl;     
cout<<mystrcmp("A","B")<<endl;     
cout<<mystrcmp("AB","A")<<endl;

return 0;     
}

int mystrcmp(const char *s1, const char *s2)
{
 while (*s1==*s2)
 {
  s1++;
  s2++;
 }

 if(*s1=='\0')
  return(0);

 return(*s1-*s2);
}
4

4 に答える 4

10

nulループが終了文字を超えて続くため、両方の入力が同一の場合はクラッシュします。

これを修正するには、ループnulの文字を次のようにチェックする必要があります。

while (*s1==*s2) {

  // if s1 points to nul character, then s2 should also, because of the ==
  // which means we've reached the end of the strings and they are equal
  // so return 0.
  if(*s1=='\0')
    return 0;

  s1++;
  s2++;
 }

 return *s1-*s2;
于 2010-10-19T04:24:33.343 に答える
3

NULmystrcmpターミネータのテストはループの外側にあるため、文字列の末尾から問題なく実行されます。文字列が同じ場合、 と の両方*s1*s20 になり、ループが続行されます。

于 2010-10-19T04:22:49.693 に答える
3
while (*s1==*s2)
{
 s1++;
 s2++;
}

'\0' == '\0'

于 2010-10-19T04:23:10.150 に答える
1

2 つの文字列が次のようになっているとどうなるかを考える必要があります。

s1:this is a string\0|abcdef
s2:this is a string\0|abcdef
       good memory <-|-> bad memory

内容が等しいときにポインタを進めるだけなので、未定義の方法でメモリを読み取ることになる可能性があります。

より良い方法は、次の疑似コードに基づいてコードを作成することです。

def strcmp(s1,s2):
    while character at s1 is not '\0':
        if character at s1 is not the same as character at s2:
            exit while loop
        increment s1 and s2
    return difference between *s1 and *s2

これは、最初の文字列の終わりに到達するか、違いを見つけると停止します (最初の文字列よりも前に 2 番目の文字列の終わりに到達した場合を含む)。

于 2010-10-19T04:25:22.453 に答える