Click here to Skip to main content
15,908,020 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I declare a pointer in C, after pointing it to an address I can see the address using the statement:

C++
int *ptr = &var;
printf("%p", ptr);


That will print the address stored in ptr will be printed.
How do I do the same in C++?

I had used a character pointer to point to dynamically allocated memory. I want to the address from which the memory begins.

What I have tried:

I tried to find from internet to do it but couldn't find anything.
Posted
Updated 6-May-20 23:41pm
Comments
[no name] 7-May-20 4:31am    
try void *ptr= &var
KarstenK 7-May-20 9:12am    
in your case it is better to use a 'char *p' so everyone (even the compiler) is knowing what you are doing ;-)

Try
cout << reinterpret_cast<void *>(p) << endl;
 
Share this answer
 
Comments
Zeeking99 7-May-20 9:36am    
Thank You, It works.
My method is a little more basic than Carlo's:
C++
cout << "Pointer value: " << hex << ptr << endl;

However, C++ still supports the printf function.
 
Share this answer
 
Comments
Zeeking99 7-May-20 9:34am    
How does it work? Can you explain it please? I didn't understand how to use it. Thank You.
Richard MacCutchan 7-May-20 10:25am    
The hex operator tells the output writer to print the next number in hexadecimal notation. And the next parameter is a pointer which is a memory address, i.e a number.
CPallini 7-May-20 15:58pm    
OOOOPS...
My 5.
Zeeking99 8-May-20 0:26am    
I understand it now except that it isn't working on my machine. My text editor isn't highlighting the word hex. Usually that means it's not a keyword of the language. Does this hex operator come with a specific version of C++?
Thank You for the answer.
Richard MacCutchan 8-May-20 3:12am    
The hex operator is a standard member of the ios class. See <ios> functions | Microsoft Docs[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900