0

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 = 
4
  • Please edit your question to contain the actual output. Commented Dec 20, 2013 at 5:30
  • 5
    Also note that ++as and the following *as results in undefined behavior. Commented Dec 20, 2013 at 5:31
  • Your question does not have relation to your code because you have not shown the area of the code that is not giving correct output Commented Dec 20, 2013 at 5:32
  • I get a warning codepad.org/HCtDIYHQ Commented Dec 20, 2013 at 5:32

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

4 Comments

what exactly does c_str() do?
@Bbvarghe c_str() (link to documentation) returns a null-terminated pointer to the character representation of the string.
also, does making *as a const still mean the value of as can still be modified?
@Bbvarghe Writing to pointer obtained through c_str() is undefined behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.