AvinashK
AvinashK

Reputation: 3423

name of string as a pointer to its first character

Given

string name="avinash";  
cout<<&name;  

If name is a pointer to a then how are we using address on a pointer?

Upvotes: 0

Views: 261

Answers (4)

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76848

  1. name is not a pointer, it is an object of type std::string. &name gives you the address of that object.
  2. To obtain a (const-)pointer to the first character of the string, use name.c_str().
  3. Pointers have addresses too!

    int i = 5;
    int *j = &i;
    int **k = &j;
    

    This is useful if you want to pass a pointer to a function that has to manipulate that pointer (for instance by allocating memory):

    void allocate_string(std::string **foo) {
        *foo = new std::string();
    }
    

Upvotes: 2

Sanja Melnichuk
Sanja Melnichuk

Reputation: 3505

Hi string class have c_str() method. Use const char* ptr = name.c_str();

Upvotes: 0

Jon
Jon

Reputation: 437554

name is not a pointer, it's the std::string itself. So &name is the address of that string, which means that this code will print out a number.

Even if it were a pointer, using operator & on it would be perfectly legal: it would return the address of the pointer variable in memory (another, different, number).

If you want a pointer to the first character inside name, then use name.c_str() to get a C-style null-terminated string (which is actually a pointer to the first character of a string), or name.data() which returns a pointer to the string but doesn't guarantee that it will be null-terminated.

Upvotes: 7

Graeme Perrow
Graeme Perrow

Reputation: 57268

name is not a pointer, name is a std::string object. &name, which is a pointer, is the address of that object.

Upvotes: 3

Related Questions