Click here to Skip to main content
15,904,339 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to convert the int* pointer to a string type.
C++
<pre>#include <iostream>
#include <string>

int main(){
  int a=7;
  const int *ptr=&a;
  std::string address_a=static_cast<const int*>(ptr);
  std::cout<<address_a<<std::endl;
}




What I have tried:

I tried also stringstream aproach but I didn't reach a result
Posted
Updated 22-Sep-19 4:04am
Comments
Rick York 22-Sep-19 11:39am    
Are you certain this is what you really want to do? I ask because an address of data in one process has no validity in any other process. In addition, if you were to put data in shared memory, two different processes would be unlikely to get the same address for the same data.

So, let's assume you have the address of your data in a string. What are you going to do with it next?

You cannot cast a number to a string. You need to use a print method to get it converted. You can do it with cout or by using a stringstream type.
C++
std::cout << ptr << endl;
 
Share this answer
 
Comments
Member 13277493 22-Sep-19 3:43am    
I need that conversion for creating my hash function, but if it is not possible, then I will think another hashing function, thanks!
Richard MacCutchan 22-Sep-19 3:51am    
My answer explains how you can convert it. What part do you not understand?
Member 13277493 22-Sep-19 3:56am    
Sorry, I misunderstood the answer. I will try and see if there will be any problems.
Richard MacCutchan 22-Sep-19 4:32am    
It would help us to help you if you explained what you are trying to do.
Member 13277493 22-Sep-19 11:53am    
I just wanted to build a hash function for linked list nodes, which would take as an input their addresses and gave me hashTable index
What's wrong with the stringstrem approach?
Try:
C++"
#include <iostream>
#include <sstream>
#include <string>

int main(){
  int a=7;
  const int *ptr=&a;

  std::ostringstream oss;
  oss  << ptr;
  std::string address_a = oss.str();
  std::cout<<address_a<<std::endl;
}
 
Share this answer
 
Comments
Member 13277493 22-Sep-19 11:52am    
thank you! My stringstream approach was different, I didn't know about str() function, I should have studied stringstream well before using it.
CPallini 22-Sep-19 16:53pm    
You are welcome.

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