Weird Pointer Address for Individual Struct Data Member

后端 未结 2 493
耶瑟儿~
耶瑟儿~ 2021-01-24 18:35

I observe some weird behavior today , the code is as follow :

The Code :

#include 

struct text
{
    char c;
};

int ma         


        
相关标签:
2条回答
  • 2021-01-24 18:53

    Consider fixing the code like this:

    std::cout << "The Address \t: " << (void *)Cptr << std::endl ;
    

    There's a std::ostream& operator<< (std::ostream& out, const char* s ); that takes a char* so you have to cast to void* to print an address, not a string it "points" to

    0 讨论(0)
  • 2021-01-24 18:58

    I think the "weird" stuff shows up because cout thinks it's a cstring, i.e. a 0-terminated character array, so it doesn't print the address as you expected. And since your "string" isn't 0-terminated, all it can do is walk the memory until it encounters a 0. To sum it up, you're not actually printing the address.

    Why I can still change the value of the member c by dereferenncing the pointer which has weird address

    The address isn't weird, as explained above. In your code Cptr points to a valid memory location and you can do pretty much anything you want with it.

    0 讨论(0)
提交回复
热议问题