简体   繁体   中英

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?

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.

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

  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(); } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM