Hi everyone, in this piece of code, ch is a pointer that points to a character. I understand that *ch is A, but why ch the pointer itself is also A? Shouldn't it be the memory address of A?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// CPP program to demonstrate working of
// reinterpret_cast
#include <iostream>
usingnamespace std;
int main()
{
int* p = newint(65);
char* ch = reinterpret_cast<char*>(p);
cout << *p << endl; //65
cout << *ch << endl; //A
cout << p << endl; //0x1609c20
cout << ch << endl; //A
return 0;
}
Also, the following prints 12. I'm not sure why. Thank you for your help.
For your second code it is up to the compiler to determine how big this struct is. It looks like it is 4 bytes for each int, 1 for the char, 1 for the bool, ... then align on the next 4-byte boundary. Check that by changing the contents first to bool b, d, e; // still outputs 12
then bool b, d, e,f; // outputs 16
but why ch the pointer itself is also A? Shouldn't it be the memory address of A?
No. operator<<(ostream&, char*) is overloaded to interpret the char* as a null-terminated c-string. So your line 11 is actually undefined behavior, because it goes past valid memory until it finds a null character.
This overload is very useful to allow printing things like std::cout << "c_string";.
If you want to print the address do std::cout << reinterpret_cast<void*>(char_pointer);
Also, the following prints 12. I'm not sure why.
It's printing the size of the struct, which happens to be 12.
12 happens to be (4 + 4 + 1 + 1) + [padding], most likely with the compiler putting in padding to make the size divisible by 4. It's up to the implementation of your compiler to say just how big a struct/class is. sizeof foo is a compile-time constant.