首页 文章

错误C2664:'strcmp':无法将参数2从'char'转换为'const char *'

提问于
浏览
1

我需要有关该脚本的帮助 .

BOOL Checking(LPCSTR MacID) {
    char ClientMacs[18] = { "11:22:33:44:55:66",};

    for(int x=0; x < 10; x++) {
        if(!strcmp(MacID, ClientMacs[x])) {
            printf(MacID," Successed!");
            return true;
        }
    }

    return false;
}

我越来越

错误C2664:'strcmp':无法将参数2从'char'转换为'const char *'从积分类型转换为指针类型需要reinterpret_cast,C风格的转换或函数式转换

当我尝试编译它 .

6 回答

  • 1

    if(!strcmp(MacID, ClientMacs[x])) {    }
    

    if(!strcmp(MacID, &ClientMacs[x])) { ... }
    

    Arg 2必须是char *,但你将它作为char . 如果你的arg 2是普通的

    ClientMacs  // compiler understands that this is shorthand for &ClientMacs[0]
    

    没关系 . 但是当索引不是零时,你必须把它放在&符号上 .

    • 皮特
  • 0

    还有&缺少...非指针< - >指针

    BOOL Checking(LPCSTR MacID) {
    
        const char* ClientMacs[18] = { "11:22:33:44:55:66",};
    
         for(int x=0; x < 10; x++) {
    
             if(!strcmp(MacID, ClientMacs[x])) {
    
                  printf(MacID," Successed!");
    
                  return true;
    
             }
    
        }
    
        return false;
    
    }
    

    也许

  • 1

    我认为你不太了解字符串(或指针)在C中是如何工作的 .

    您正在尝试将字符数组的单个字符与传入的字符串进行比较:

    if(!strcmp(MacID, ClientMacs[x])
    
  • 3
    if(!strcmp(MacID, ClientMacs[x]))
                    // ^^^^^^^^^^^ gives the character at index x
    

    可能你的意思是 -

    if(!strcmp(MacID, &ClientMacs[x]))
                    //^  Added & symbol
    

    鉴于 printf 语句,我认为,没有必要逐字逐句地进行比较 . 不需要循环 . 这可以是 -

    for(int x=0; x < 10; x++) {
        if(!strcmp(MacID, ClientMacs[x])) {
            printf(MacID," Successed!");
            return true;
        }
    }
    

    浓缩为 -

    if(!strcmp(MacID, ClientMacs)) {  // Changed ClientMacs[x] to ClientMacs
        printf(MacID," Successed!");
        return true;
    }
    
  • 1

    ClientMacs需要是一个指向字符(字符串指针)的指针数组,而不是一个字符数组 . 您也可以使用LPCSTR typedef,因为您还将它用于函数参数 .

    试试这个:

    BOOL Checking(LPCSTR MacID) {
    
        LPCSTR ClientMacs[18] = { "11:22:33:44:55:66", [put the other 9 (or is it 17?) MAC address strings here]};
    
        for(int x=0; x < 10; x++) {
    
             if(!strcmp(MacID, ClientMacs[x])) {
                printf(MacID," Successed!");
                return true;
             }
        }
    }
    

    你的命名通常非常糟糕,但我没有改变它 .

  • 1

    由于你've tagged this C++, I' d建议完全不使用 strcmp ,而是使用 std::string 代替:

    std::set<std::string> ClientMacs;
    
    ClientMacs.insert("11:22:33:44:55:66");
     // presumably insert more MAC addresses here
    
    
    bool check(std::string const &MacID) {    
        if (ClientMacs.find(MacID) != ClienMacs.end()) {
            std::cout << "Success!";
            return true;
        }
    }
    

    但是,我应该补充一点,你在这里想要完成的事情并不完全清楚 . 我的假设是您有一个可能的MAC地址列表(例如,本地网络中的所有计算机),并且您正在尝试验证您收到的MAC地址(例如,在以太网数据包中)是否匹配其中一个那些(例如,防火墙的一些东西,将确保只接受来自已知来源的数据包) .

相关问题