Reputation: 339
I have a problem with address of a pointer.
class:
class name{
public:
name();
}
I want to get address of a pointer of the name class and convert it to string
name* p=new name();
const char* add=(const char*)&p;
printf("%s \n",add); // input is ������� . how to transfer add to string to use printf("%s \n",add) and result is 0xbfa0f108 ??
printf("%p \n",add); //input is 0xbfa0f108
name *q;
q= add; // i want to assign the address of q to point to p. indirect via add.
How do i need to do? I am a new in c++;
Upvotes: 1
Views: 9631
Reputation: 433
To get the string of the address of a pointer to the name class, you just write:
name* p = new name(); // pointer to name class
const char* add = reinterpret_cast<const char*>(&p);
std::string str = add;
You can retrieve an address to an object in a couple ways:
type* pntr = &object;
In the above example, pntr is now an address to object. The & symbol, when used on the right hand side of a statement, specifies that you want an address. When used on the left hand side of a statement, & specifies a reference to another object:
type& ref = object;
In this example, ref is now a reference to object. Setting ref equal to another value will set object equal to that value.
When you have a pointer, and you want the object that that pointer points to, just use the * symbol to dereference the pointer:
type* pntr = &object; // pntr is the address pointing to object
std::cout << *pntr << std::endl; // dereferences pntr to retrieve object
Like @vishal said, q = add will throw an error because you are assigning a const char* to a name*. You can't directly assign one type of pointer to another type like this. Also, casting away const is not considered bad practice, but you must be absolutely certain that you know what you are doing. It is, however, considered bad practice to use C-style casts in c++. If you want to cast, you should use one of the following:
static_cast<type*>(pointerToSomeOtherType);
reinterpret_cast<type*>(pointerToSomeOtherType);
const_cast<type*>(pointerToSomeOtherType);
dynamic_cast<type*>(pointerToSomeOtherType);
not
(type*) pointerToSomeOtherType;
Upvotes: 4
Reputation: 2391
If you want to print the address of the pointer just use &.
change:
printf("%s \n",add);
to:
printf("%p \n",&add);
or better use cout //as this question is tagged to c++
cout<<&add;
i want to assign the address of q to point to p. indirect via add.
well you cannot do:
q = add; // name * and const char ** are different pointer types.
You can assign q as reference to add by casting it to name *
q= (name *) &add; // not a good practice
cout<<q<<endl;
this is not a good practice for casting const char * because:
const char is a pointer, who's value can be also changed, that points to a location containing a value of type char that cannot be changed.*
Upvotes: 0