2013-12-20 24 views
0

我写了一个简单的程序来看看C++如何处理字符串对象的指针(OOP中的新对象),我惊讶地发现那个是string* as这是分配内存地址string a,没有存储相当于&a的值。此外,控制台未将值打印到*as。这可能是我的最终或系统上的错误,或者在这里错过了一些基本的东西?C++字符串指针与它指向的字符串没有相同的内存地址

#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; 
} 

输出:

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

请编辑您的问题以包含实际输出。 –

+5

另请注意'++ as'和下面的'* as'会导致未定义的行为。 –

+0

你的问题与你的代码没有关系,因为你没有显示没有给出正确输出的代码区域 – smac89

回答

4

在我的程序的有效部分的测试(的cout前两行),打印输出表现出相同的地址:

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

link to a demo

然而,第三和第四行相当于未定义的行为vior:一旦你做了++as,你就将指针移动到下一个std::string的“字符串数组”(不存在)。因此,后续尝试解除引用as未定义的行为

如果你想获得一个指向您的字符串的数据,例如,你可以通过增加指针移动到下一个字符,你可以使用c_str()成员函数,就像这样:

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

c_str()到底做了什么? – Bbvarghe

+0

@Bbvarghe'c_str()'([link to documentation](http://en.cppreference.com/w/cpp/string/basic_string/c_str))返回一个以空字符结尾的字符串表示形式的指针。 – dasblinkenlight

+0

也,作为一个'const'仍然意味着'as'的值仍然可以被修改? – Bbvarghe