-3

My function transforms hex symbol into string of 2 characters, then breaks it into 2 strings of 1 characters. When I compare resulted string with constant string, I get an error: Cannot convert 'unsigned char' to 'char *' first_ascii_code = 0x30;

compiler: C++ Builder 6

code:

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;
}

How can I correct this error?

KatieK
  • 13,586
  • 17
  • 76
  • 90

2 Answers2

3

The test broken_input_byte[0] == "0" is incorrect. You probably want to test if the first character is the '0' char, so you should code broken_input_byte[0] == '0' (assuming BYTE, an implementation specific name, is typedef-ed to char).

In C, any test like foo == "string" is certainly wrong; it is an undefined behavior, because "string" is in fact the address of some constant string literal data, so such a test would compare the pointer foo to some constant pointer (and even "aa" == "aa" could be false, because the compiler might build two constant strings "aa" located at different addresses!). BTW, with a recent GCC compiler you get a warning (when compiling with gcc -Wall) on it.

You probably want to use strcmp to compare null-terminated strings.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • It is not undefined behavior to compare two arbitrary pointers for equality, though as you say, it is wrong here. I would also mention that `broken_input_string` is not a large enough buffer to hold the result of the call to `itoa`. – Ed S. Oct 05 '12 at 05:27
  • But it is UB to compare a pointer against a constant literal string. – Basile Starynkevitch Oct 05 '12 at 05:32
  • Oops, you're right, I missed that. I believe it's unspecified behavior though, not undefined. – Ed S. Oct 05 '12 at 05:34
1

"0" is a string not character in C while broken_input_byte[0] is a BYTE equivalent to char in C, so both are not same type hence the error.

If you want to compare strings strcmp is the function not == operator.

Rohan
  • 52,392
  • 12
  • 90
  • 87