是什么导致错误“无法转换'unsigned char'”?

时间:2012-10-05 05:10:09

标签: c

我的函数将十六进制符号转换为2个字符的字符串,然后将其分成2个1个字符的字符串。当我将结果字符串与常量字符串进行比较时,出现错误:Cannot convert 'unsigned char' to 'char *' first_ascii_code = 0x30;

编译器:C ++ Builder 6

代码:

BYTE from_byte_to_ascii_codes(int input_byte);
// transformation hex into string with of 2 characters and then 
// its transformation into 2 hex bytes. compiler - C++ Builder 6

BYTE from_byte_to_ascii_codes(int input_byte)
{
BYTE broken_input_byte[] = "";
input_byte = 0x01;
itoa(input_byte, broken_input_byte, 16);
// now broken_input_byte[] = "01";
if (broken_input_byte[0] == "0") { // here is mistake   
//Cannot convert 'unsigned char'  to 'char *'
first_ascii_code = 0x30;
}

如何更正此错误?

2 个答案:

答案 0 :(得分:3)

测试broken_input_byte[0] == "0"不正确。您可能想要测试第一个字符是否为'0'字符,因此您应该编写broken_input_byte[0] == '0'代码(假设BYTE,一个特定于实现的名称,typedef - 编辑为{ {1}})。

在C中,任何像char这样的测试肯定是错误的;它是undefined behavior,因为foo == "string"实际上是某些常量字符串文字数据的地址,因此这样的测试会将指针"string"与某个常量进行比较指针(甚至foo可能是false,因为编译器可能会在不同的地址构建两个常量字符串"aa" == "aa"!)。顺便说一句,使用最近的GCC编译器,你会收到警告(当用"aa"进行编译时)。

您可能希望使用strcmp来比较以null结尾的字符串。

答案 1 :(得分:1)

"0"C中不是字符的字符串,而broken_input_byte[0]BYTEchar的{​​{1}},因此两者都不是C相同的类型因此错误。

如果您想比较字符串strcmp,则函数不是==运算符。

相关问题