question about reinterpret_cast

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> 
using namespace std; 
  
int main() 
{ 
    int* p = new int(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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct mystruct { 
    int x; 
    int y; 
    char c; 
    bool b; 
}; 
  
int main() 
{ 
    mystruct s; 
  
    // Assigning values 
    s.x = 5; 
    s.y = 10; 
    s.c = 'a'; 
    s.b = true; 
  
    int* p = reinterpret_cast<int*>(&s); 
  
    cout << sizeof(s) << endl; 
}
Last edited on
For your first code, it treats it as a c-string:
http://www.cplusplus.com/reference/ostream/ostream/operator-free/
(in which case it may be undefined behaviour, as you haven't null-terminated).

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
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.