-5
我练我的“代码高尔夫”或编程面试样题,并不能找出为什么我在下面得到一个分段错误:这个程序中的段错误的原因是什么?
#include <iostream>
bool contained (char * str1, char * str2)
{
// returns true or false depending on whether the string str1 is contained in str2
while (str2)
{
if (*str1 == *str2)
{
char * temp = str2;
while (*str1++ == *temp++);
if (!*str1) return true;
}
else
{
++str2;
}
}
return false;
}
int main()
{
char sa [] = "abc";
char sb [] = "rehabc132";
std::cout << contained(sa, sb); // should print out 1
return 0;
}
证明:http://codepad.org/5Ff3qTIX
任何想法为什么?
由于第二个字符串更长,所以您正在运行超过第一个字符串的末尾... –
此外,您可能是指'while(* str2)'? –
'* str1 ++'嵌套在两个循环中,所以最终会跑出该字符串的末尾。 –