簡體   English   中英

“unsigned char *”類型的參數與“const char *”類型的參數不兼容

[英]Argument of type "unsigned char *" is incompatible with parameter of type "const char *"

我使用的是 Microsoft Script Encoder 的解碼器。 當我在 Codeblocks 中運行它時,它運行良好。 但是當我在 Visual Studio 中運行它時,它顯示了以下錯誤
片段 1:

char decodeMnemonic(unsigned char *mnemonic)
{
    int i = 0;
    while (entities[i].entity != NULL)
    {
        **if (strcmp(entities[i].entity, mnemonic) == 0)**
       **//Error 1: cannot convert argument 2 from 'unsigned char *'
       // to 'const char *'**   
        return entities[i].mappedchar;
        i++;
    }
    printf("Warning: did not recognize HTML entity '%s'\n", mnemonic);
    return '?';
}

我必須將解碼器集成到程序中,因此我沒有將文件名作為命令行參數傳遞,而是在代碼中自己提供了它們的文件路徑。

片段 2:

    int main()
    {
        unsigned char *inname = "C:\\Users\\Karthi\\Desktop\\Project Winter 2018-19\\poweliks_sample\\poweliks_encoded_js.bin";
        unsigned char *outname = "C:\\Users\\Karthi\\Desktop\\Project Winter 2018-19\\poweliks_sample\\decoded1.txt";
        unsigned int cp = 0;
   //**Error 2: 'initializing': cannot convert from 'const char [87]' to 'unsigned char *'**    

您可以使用reinterpret_cast (對於unsigned char*const char* )。 但是,如果您從const unsigned char*轉到非const類型,則必須首先使用const_cast ,因為reinterpret_cast無法丟棄const

下面的段落簡要概述了為什么您的代碼不起作用。

根據C99 標准(類似於其他 C 標准),字符串文字具有靜態存儲持續時間,其類型為char[]標准說:

如果程序嘗試修改這樣的數組,則行為未定義。

當您使用argv時,您的程序工作的原因是,該argv不被視為字符串文字數組。 這意味着您可以修改它們。

以下是針對您的問題的解決方案:

代碼段 1: strcmp 是一種比較兩個 C 字符串的方法。 它需要 const char* 類型。

int strcmp ( const char * str1, const char * str2 ); 你有兩個選擇來解決它:

  1. 像這樣聲明你的方法

    char decodeMnemonic(const char *mnemonic)
  2. 使用 C++Strings 並像這樣聲明你的方法

    char decodeMnemonic(std::string mnemonic)

如果使用第二種解決方案,則必須調用 c_str()-Method 才能在 strcmp 中使用它

if (strcmp(entities[i].entity, mnemonic.c_str()) == 0)

或者你只使用 C++-String:在這里閱讀如何使用它: http : //www.cplusplus.com/reference/string/string/compare/

代碼段 2:您不能像這樣使用它,因為您有字符串文字,它們是數組常量字符。 請使用 C++-Strings。 您使用 C++,因此請使用他的功能( https://www.geeksforgeeks.org/stdstring-class-in-c/

無論如何,如果你想像 C 一樣使用它: https : //www.programiz.com/c-programming/c-strings

char c[] = "abcd";
char c[50] = "abcd";

或使用 const (C++)

char *str1 = "string Literal";
const char *str2 = "string Literal";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM