Search code examples
c++pointersstructpointer-address

Weird Pointer Address for Individual Struct Data Member


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.


Solution

  • 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