leetcode实现strstr c++返回指针
leetcode implemente strstr C++ return pointers
实现strStr().
返回一个指针,指向第一次出现在haystack中的needle,如果needle不是haystack的一部分,则返回null。
我写的:
class Solution {
public:
char *strStr(char *haystack, char *needle) {
std::string s1(haystack);
std::string s2(needle);
if(s2.empty())
{return haystack;}
int a = s1.length();
int b = s2.length();
if(a < b)
{return NULL;}
for(int i = 0; i < a - b; i++)
{
int j = 0;
int k = i;
while(j < b && s2[j] == s1[k])
{
k++;
j++;
}
if(j == b)
{return (char*) s1[i];}
}
else return NULL;
}
};
但是Leetcode给了我编译错误:警告:从不同大小的整数转换为指针[-Wint-to-pointer-cast]
…我应该返回一些其他的东西吗?.....
return (char*) s1[i];
有两个问题。首先,将字符的值转换为指针。您希望返回字符的地址,而不是将其值转换为指针。其次,s1
是从haystack
参数初始化的本地std::string
。您不希望返回指向其中一个字符的指针,因为一旦函数返回,它将超出作用域。您需要一个指向原始haystack
c-string中的字符的指针。
return &haystack[i];
如果您将string
想象为一个字符序列,那么(char*) s1[i]
实际上是在代码段
char -> char *
if(j == b)
{return (char*) s1[i];}
operator[]
返回字符串的第i个字符。(http://www.cplusplus.com/reference/string/string/, http://www.cplusplus.com/reference/string/string/operator[]/)
相关文章:
- 在函数中返回无符号字符数组,但不返回指针
- 为什么需要返回指针来利用协方差?
- 野牛如何在解析树中返回指针
- 何时返回指针与返回对象的一般经验法则?
- 为什么使用 std::istream_iterator 构造函数返回指针
- 为什么我不能直接从返回指针的函数返回对指针的引用?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 使用 map<char,strring> 的迭代器返回指针 map<char,strring>*
- 如何从类成员函数返回指针,例如 size_t * class :: function(); 并使用类析构函数 ~size
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- 从函数返回对指针的引用与返回指针相同?
- C++ 为什么访问数组中的元素会返回指针?
- 关于函数返回指针
- 返回指针或对私有成员的引用的替代方法
- 从函数返回指针
- 通过从当地的C风格阵列中返回指针来获取一个悬空的指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 为什么C 模板功能不支持返回指针
- 返回指针的语句 - 解释它是如何工作的以及为什么