我正在使用strstr()函数,但我遇到了崩溃。
这部分代码崩溃,错误为“访问冲突读取位置0x0000006c”
strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))
这是完整的代码。。。

#include "stdafx.h"
#include <iostream>
#include <string>
void delchar(char* p_czInputString, const char* p_czCharactersToDelete)
{
    for (size_t index = 0; index < strlen(p_czInputString); ++index)
    {
        if(NULL != strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))
        {
            printf_s("%c",p_czInputString[index]);

        }
    }
}
int main(int argc, char* argv[])
{
    char c[32];
    strncpy_s(c, "life of pie", 32);
    delchar(c, "def");

    // will output 'li o pi'
    std::cout << c << std::endl;
}

最佳答案

strstr()的原型如下:,

char * strstr ( char * str1, const char * str2 );

该函数用于从主字符串定位子字符串。它返回指向str2中第一个出现str1的指针,如果str2不是str1的一部分,则返回空指针。
在您的例子中,您将错误的参数传递给strstr()。你在打电话,
strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]));,这是错误的。因为指针p_czCharactersToDelete指向子字符串常量,p_czInputString指向主字符串。调用strstr()作为strstr(p_czInputString, p_czCharactersToDelete);并在函数delchar()中进行相应的更改。

关于c++ - 使用strstr()函数中断,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16749071/

10-15 05:13