Sas
Sas

Reputation: 1

Why char array is not printing value?

I need to read back 'id' and 'port' from char array. But cout does not print anything. What is the correct way to do it?

Thank you for your help.

int main() {
    char addr[6];
    int id = 2;
    short port = 1;
    memcpy(&addr[0], &id, sizeof(int));
    memcpy(&addr[4], &port, sizeof(short));

    cout << "addres:" << addr << endl;
    return 0;
}

Upvotes: 0

Views: 1024

Answers (2)

R Sahu
R Sahu

Reputation: 206607

You can print the integral values of the contents of addr to understand what's there.

for (int i = 0; i < 6; ++i )
{
    std::cout << "element " << i << " : " << static_cast<int>(addr[i]) << std::endl;
}

You will most likely get:

element 0 : 2
element 1 : 0
element 2 : 0
element 3 : 0
element 4 : 1
element 5 : 0

That assumes that:

  1. sizeof(int) is 4 on your platform.
  2. sizeof(short) is 2 on your platform.
  3. Your platform uses little endian system for numbers.

When you use

    cout << "addres:" << addr << endl;

You are printing a string that has an unprintable character in the first element and a null character at the second element, i.e. you are printing a null terminated string that contains only a non-printable character.

Upvotes: 0

Max Vollmer
Max Vollmer

Reputation: 8598

Because, assuming int is 32 bit on your target platform, you are copying 4 bytes (0, 0, 0, 2 or 2, 0, 0, 0, depending on endianness) into the address pointed to by addr, and assuming short is 16 bit, you are copying 2 bytes (0, 1 or 1, 0, depending on endianness) at the address pointed to by addr+4, causing addr to contain the bytes 0, 0, 0, 2, 0, 1 or 2, 0, 0, 0, 1, 0.

C-style strings in C++ are 0-terminated, so if the first char is 0, addr is interpreted as an empty string.

If the first char is 2, you still won't see anything, because that's not a printable character. (It's the control character STX (Start of Text).)

Upvotes: 3

Related Questions