gpt4 book ai didi

c++ - 无效的空指针

转载 作者:行者123 更新时间:2023-11-28 07:15:22 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来解析字符串并给出单词的每个位置。我不明白为什么我得到一个

"DEBUG ASSERTION FAILED" Experssion: Invalid null pointer

当它到达字符串的最后一个单词时窗口。

char * pointer_char;
int pos = 0;
std::string str = "This test string will fail at this word..!. ";

int i = 0;
int length = str.length();

char * c = new char [str.size()+1];
std::copy(str.begin(), str.end(), c);
c[str.size()] = '\0';

cout << "Testing string is " << str << endl << endl;
pointer_char = strtok (c," ");
while(pointer_char != NULL)
{
cout << pointer_char << endl;
pointer_char = strtok(NULL, " .!");
string word = pointer_char;

size_t found= str.find(word);
if (found!=string::npos)
cout << "Position of " << word << " found at: " << int(found) << endl;
system("pause");
}
return 0;

最佳答案

问题是您没有检查 strtok 的返回值。

    pointer_char = strtok(NULL, " .!");
string word = pointer_char;

您只在循环的顶部测试它。

    pointer_char = strtok(nullptr, " .!");
if (pointer_char == nullptr)
break;

关于c++ - 无效的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com