Weird Pointer Address for Individual Struct Data M

2020-04-21 05:33发布

问题:

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.