简体   繁体   English

字符串名称,作为指向第一个字符的指针

[英]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是指向a的指针,那么我们如何在指针上使用地址?

name is not a pointer, it's the std::string itself. name不是指针,而是std::string本身。 So &name is the address of that string, which means that this code will print out a number. 因此, &name是该字符串的地址,这意味着此代码将打印出一个数字。

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). 即使它是一个指针,也可以在其上使用operator &完全合法:它将返回指针变量在内存中的地址(另一个数字)。

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第一个字符的指针,请使用name.c_str()获得一个C样式的以空字符结尾的字符串(实际上是一个字符串的第一个字符的指针),或者name.data()它返回一个指向字符串的指针,但不保证该字符串将以null终止。

name is not a pointer, name is a std::string object. name不是指针,名称是std::string对象。 &name , which is a pointer, is the address of that object. &name 一个指针,是该对象的地址。

  1. name is not a pointer, it is an object of type std::string . name不是指针,它是std::string类型的对象。 &name gives you the address of that object. &name为您提供该对象的地址。
  2. To obtain a (const-)pointer to the first character of the string, use name.c_str() . 要获得指向字符串第一个字符的(常量)指针,请使用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. 嗨,字符串类有c_str()方法。 Use const char* ptr = name.c_str(); 使用const char* ptr = name.c_str();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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