Weird Pointer Address for Individual Struct Data Member

喜欢而已 提交于 2019-12-04 05:01:53

问题


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

The Code :

#include <iostream>

struct text
{
    char c;
};

int main(void)
{
    text experim = {'b'};
    char * Cptr = &(experim.c);

    std::cout << "The Value \t: " << *Cptr << std::endl ;
    std::cout << "The Address \t: " << Cptr << std::endl  ; //Print weird stuff

    std::cout << "\n\n";

    *Cptr = 'z';   //Attempt to change the value

    std::cout << "The New Value \t: " << *Cptr <<std::endl ;
    std::cout << "The Address \t: " << Cptr << std::endl ; //Weird address again

    return 0;
}

The Question :

1.) The only question I have is why cout theAddress for the above code would come out some weird value ?

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

Thank you.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/11699430/weird-pointer-address-for-individual-struct-data-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!