0

I am writing a very simple code to test the Hex data on c++

int main()
{
    unsigned char bytestosend[4] = {0xB5, 0x62, 0x06, 0x08};

    cout << &bytestosend << endl;
}

The data that comes on the terminal is : 0xbfa1ef58

how could this happen ? and when I remove the '&' it gives me strange symbols

1
  • Using the ampersand is giving you the memory location of your array, not the contents of it. If you remove the ampersand, you're printing a non-null-terminated string Commented May 27, 2013 at 13:51

2 Answers 2

5

When you use the & it is outputting the address of the array and when you don't it is printing it as ASCII data.

Sign up to request clarification or add additional context in comments.

7 Comments

Doesn't it also need a null byte 0x0?
Yes, it will most likely print a bunch of gibberish as it goes off the end of the array.
@0x499602D2 Only string literals initialized with "..." have a terminating null character put in for you.
@GuyGreer Yes I know but since he's using a char array and he isn't initializing it with a string literal, isn't he suppose to explicitly add the null byte?
@0x499602D2 If he wants to be able to use it as a string, yes.
|
1

The '&' means 'address of' in this context. You are printing the location of bytestosend in memory rather than the contents of it.

Remove that '&' and you won't get what you want either. Now that stream insertion operator (operator >>) sees a char array, so it's going to try to print your array as if it was a string. Your array isn't null terminated, so that output might go on for a while.

If you want to print all four of the elements of bytestosend in hex use something like this:

std::cout.flags (std::ios::hex | std::ios::showbase);
std::cout << int(bytestosend[0]) << ", "
          << int(bytestosend[1]) << ", "
          << int(bytestosend[2]) << ", "
          << int(bytestosend[3]) << std::endl;

2 Comments

Oops. Code fixed. std::ostream & operator<<(char) interprets the input as a char rather than an integer. You need to cast to non-char integral type to have the input interpreted as a number rather than a character.
Zeyad Serag - You do not need those brackets around int. I rolled back your edit. I prefer not to use things like (TypeName) x. This is a C-style cast. I always compile with warnings on use of C-style casts. TypeName(x) is a functional style cast. This is illegal syntax in C, but keep in mind that C++ is not C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.