Reputation: 31
This code aims to make pointer c points to the address that pointer a points to. I can't understand this expression: " char* c= (char*)&a ". Can someone please clarify it?
string* a =new string;
std::cin >> *a;
char* c= (char*)&a;
delete a;
Upvotes: 0
Views: 902
Reputation: 238351
How to store the address that a pointer points to to another pointer?
You can copy it:
T* a = some_address;
T* b = a; // copied the address from a to b
I can't understand this expression:
char* c= (char*)&a
This declares a variable of type char*
which is a pointer to char
. The name of the variable is c
. The variable is initialised with the expression (char*)&a
.
The unary &
is the addressof operator. When applied to an lvalue, it results in the address of the object named by the lvalue. In this case, you get the address of the variable a
. Note that the address of the variable a
is not the same as the address of dynamic object that a
points to. Since the type of a
is string*
, the type of the pointer to a
is string**
.
(char*)a
is an explicit conversion (aka C-style cast). In this case it performs a reinterpret cast from string**
to char*
. Without context, this conversion seems to make no sense, but it makes the example well-formed regardless. Don't use C-style casts in C++.
P.S. Avoid unnecessary dynamic allocation. If string
is std::string
, then there is hardly ever a reason to allocate it dynamically.
I'm trying to make c point to the memory address of the first letter in string *a. How do I do that?
There are no letters in a
at all. a
simply contains the address of a string
object.
If you want to point to the first character that is stored in the buffer managed by the string that is pointed by a
- with the assumption that string
is std::string
, then you can indirect through a
and use the data
member function of std::string
:
char* c = a->data();
Upvotes: 2