簡體   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