繁体   English   中英

使用strstr()函数中断

[英]using strstr() function is breaking

我正在使用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 );

该函数用于从主字符串中定位子字符串。 它返回一个指向第一次出现str2str1如果,或一个空指针str2不是部分str1

在您的情况下,您将错误的参数传递给strstr() 您正在调用, strstr(p_czCharactersToDelete, (const char*)p_czInputString[index])); ,这是错误的。 因为指针p_czCharactersToDelete指向子字符串常量,而p_czInputString指向主字符串。 调用strstr()作为strstr(p_czInputString, p_czCharactersToDelete); 并在函数delchar()进行相应的更改。

您使用了错误的strstr 可能您需要strchrstrpbrk

#include <cstring>
#include <algorithm>

class Include {
public:
    Include(const char *list){ m_list = list; }

    bool operator()(char ch) const
    {
        return ( strchr(m_list, ch) != NULL );
    }

private:
    const char *m_list;
};

void delchar(char* p_czInputString, const char* p_czCharactersToDelete){
    Include inc(p_czCharactersToDelete);
    char *last = std::remove_if(p_czInputString, p_czInputString + strlen(p_czInputString), inc);
    *last = '\0';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM