Question:
C++ How to change address stored in pointer. HELP!?
mrmoo90
2011-10-17 13:30:06 UTC
PLEASE READ ALL:

Ok. What I would like to do is store an address in a pointer variable. The address is currently saved in a string variable. Here is the code:

TreeNode* current;
string Address = "0x878F3D";
// How do I set current equal to the address stored in Address
// Note: I have tried maaany things so please don't suggest things like this:
current = Address;
// Or this
int hexadecimal;
stringstream convert (Address);
convert >> std::hex >> hexadecimal;
current = hexadecimal;

Please! I am going crazy trying to figure this out!
Three answers:
cja
2011-10-17 13:51:48 UTC
This works:



#include

#include

#include

#include



using namespace std;



template

struct TreeNode {

      T value;

      TreeNode *left;

      TreeNode *right;

};



int main(int argc, char *argv[]) {

      TreeNode *current;

      void *p1;

      string Address("0x8783FD");

      stringstream ss;



      ss.str(Address);

      ss >> hex >> p1;

      current = reinterpret_cast*>(p1);

      cout << hex << current << endl;

     

      return 0;

}



#if 0



Program output:



0x8783fd



#endif
Don't sue me!
2011-10-17 20:42:55 UTC
Here's a function that takes a string argument and returns an int:



int parseNumber(const string &num, int base, int trim)

{

int c = 1;

int n, m;

int res = 0;

for (int i = num.size() - 1; i >= trim; i--)

{

n = num[i] - '0';

if (n > 9) n -= ((n >= 'a'-'0')? 'a': 'A') - '0' - 10;



res += n*c;

c *= base;

}

return res;

}



Example:

current = (TreeNode*)parseNumber(Address, 16, 2);



Note that this function accounts for the 0x.

Even though this method will work on some platforms, it might fail on others due to the difference in size between type int and a pointer.

There are many solutions, one of them is using templates, another one is using a larger type such as long long which will work on 64-bit platforms.
Little Princess
2011-10-17 20:40:36 UTC
string Address = "0x878F3D";

int resultInt;

int *resultPtr;

char junk1, junk2;

scanf( "%1c%1c%x", &junk1, &junk2, &resultInt);

resultPtr = (int*) resultInt;



*** This is very bad to do. Depending upon what operating system you're using, attempting to access whatever's at that address is likely to trigger an exception fault. You are >99.99% likely to screwing something up even if it doesn't trigger an exception.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...