Bbvarghe
Bbvarghe

Reputation: 265

C++ string pointer doesn't have the same memory address as the string it points to

I wrote a simple program to see how C++ handles pointers to string objects (new to OOP), and I was suprised to see that string* as which was assigned the memory address of string a, didn't store a value equivalent to &a. Also, the console didn't print the value to *as. Could this be an error on my end or the system, or am missing something fundamental here?

#include    <iostream>
#include    <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;

string a = "asdf";
string* as = &a;
string* as_holder = &a;

int main()
{
    cout << "a = " << a <<  "\t" << "&a = " << &a << " *as = " << *as << endl
        << "as = " << as << endl
        << "++as = " << ++as << endl
        << "*as = " << *as << endl << endl;

    return 0;
}

output:

a = asdf     &a = 011ff68C *as = 
as = 011FF6A8
++as = 011FF6A8
*as = 

Upvotes: 0

Views: 117

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

In my test of the valid portion of your program (the first two lines of cout), the printout showed the same address:

a = asdf    &a = 0x8049c90 *as = asdf
as = 0x8049c90

(link to a demo)

Lines three and four, however, amount to undefined behavior: once you do ++as, you are moving the pointer to the next std::string in an "array of strings" (which does not exist). Therefore, the subsequent attempt at dereferencing as is undefined behavior.

If you would like to obtain a pointer to the data of your string, such that you could move to the next character by incrementing the pointer, you could use c_str() member function, like this:

const char *as = a.c_str();
as++;
cout << as << endl; // This would print "sdf"

Upvotes: 4

Related Questions