【问题标题】:Why does this char comparison cause errors?为什么这个字符比较会导致错误?
【发布时间】:2021-12-25 07:13:40
【问题描述】:

在这个函数中,我试图检查一个 char 数组是否包含广播 MAC 地址。为此,我将每个数组元素与0xFF 进行比较。

static inline bool recibir_trama_l2_en_interface(interface_t *interface, cab_ethernet_t *cab_ethernet) {
    char *mac = MAC_IF(interface);
    if(IF_EN_MODO_L3(interface)) {
        char *mac_destino = cab_ethernet->mac_destino.dir_mac;
        mostrar_dir_mac(&interface->prop_intf->dir_mac);
        mostrar_dir_mac(&cab_ethernet->mac_destino);
        bool bandera_prueba = true;
        bandera_prueba = mac_destino[0] == 0xFF;            

        if(mac_destino[0] == 0xFF && mac_destino[1] == 0xFF && mac_destino[2] == 0xFF && mac_destino[3] == 0xFF && mac_destino[4] == 0xFF && mac_destino[5] == 0xFF) {
            printf("Esto está pasando.\n");
        }
        printf("AABBNINKD.\n");
        if(mac_destino[0] == 0xFF) {
            printf("Esto sí pasa.\n");
        }    
    }
    return false;
}

这些是我正在使用的结构。

typedef struct cab_ethernet_ {
    dir_mac_t mac_destino;
    dir_mac_t mac_origen;
    short tipo;
    char payload[TAM_MAX_PAYLOAD];
    unsigned int FCS;
} cab_ethernet_t;

typedef struct dir_mac_ {
    char dir_mac[TAM_DIR_MAC];
} dir_mac_t;

调试器显示mac_destino[0] 的内容是0xFF。但是你也可以看到,经过比较,bandera_prueba 被设置为false

正在发生的另一件事是程序显然正在跳过这些指令。

if(mac_destino[0] == 0xFF && mac_destino[1] == 0xFF && mac_destino[2] == 0xFF && mac_destino[3] == 0xFF && mac_destino[4] == 0xFF && mac_destino[5] == 0xFF) {
    printf("Esto está pasando.\n");
}

if(mac_destino[0] == 0xFF) {
    printf("Esto sí pasa.\n");
}

我的意思是,调试器从第 78 行跳转到第 83 行再到第 89 行。 这种比较有什么问题会导致这些错误吗?

【问题讨论】:

  • 我想你可能希望struct dir_mac_ 使用unsigned char 类型。

标签: c debugging char


【解决方案1】:

常量0xFF 的值为255。在您的C 实现中,char 是有符号的,并且只能具有-128 到+127 的值。 mac_destino[0]char。因此mac_destino[0] == 0xFF 永远不可能是真的。在调试器中单步执行代码似乎会跳过行,因为编译器已优化程序以省略不可能的部分。

要解决此问题,请将使用的类型更改为 unsigned char

最好将struct dir_mac_dir_mac的元素类型改为unsigned charmac_destino的类型改为unsigned char *。如果您不能这样做,请将mac_destino 的定义从char *mac_destino = cab_ethernet->mac_destino.dir_mac; 更改为unsigned char *mac_destino = (unsigned char *) cab_ethernet->mac_destino.dir_mac;

如果您不能这样做,您可以在每次比较中插入一个转换,例如将mac_destino[0] == 0xFF 更改为(unsigned char) mac_destino[0] == 0xFF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    相关资源
    最近更新 更多