Reputation: 3423
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
Reputation: 76848
name
is not a pointer, it is an object of type std::string
. &name
gives you the address of that object.name.c_str()
.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
Reputation: 3505
Hi string class have c_str() method.
Use const char* ptr = name.c_str();
Upvotes: 0
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
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