0
点赞
收藏
分享

微信扫一扫

LeetCode报错:Line 923: Char 9: runtime error: reference binding to null pointer of type ‘std::__cxx11:


LeetCode报错

报错原因:

Line 923: Char 9: runtime error: reference binding to null pointer of type ‘std::__cxx11::basic_string<char, std::char_traits, std::allocator >’ (stl_vector.h)

程序中具体原因:
    vector数组为空的时候,会出现这个错误。在程序中就是for语句出错,因为当数组为空时,len=0,len-1=-1,所以在for循环中会出错

出错具体代码

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();
string result="";
int i=0;
while(strs[0][i]!='\0')
{
for(int j=0;j<len-1;++j)
{
if(strs[j][i]!=strs[j+1][i])
return result;
}
result+=strs[0][i];
++i;
}
return result;
}
};

改正后代码(判断数组为空,提前return)

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();
string result="";

if(len==0) return result;// 判断是否为空

int i=0;
while(strs[0][i]!='\0')
{
for(int j=0;j<len-1;++j)
{
if(strs[j][i]!=strs[j+1][i])
return result;
}
result+=strs[0][i];
++i;
}
return result;
}
};


举报

相关推荐

0 条评论