name variable from its address

Write your question here.

l can have address ofvariable a using &a.
could l have its name from his address?
that is, if l know a variable a has address &a can l have his name a ?
Last edited on
Your debugger might be able to do it. Otherwise your code could set up an association (map) between memory locations and variable names.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
   int a, b, c, d;
   map<int*,string> loc{ { &a, "a" }, { &b, "b" }, { &c, "c" }, { &d, "d" } };
   for ( auto p : loc ) cout << p.first << "  " << p.second << '\n';
}


The memory address won't be the same every time you run the program.

I guess we need to ask ... why do you want to do this?
Last edited on
if you are dealing with objects you can self name them.

thing something("something");
thing * why = &something;
cout << *why.myname(); //assuming you populated a string with the name and a method to return it.

if its more than one object or not even objects but ints etc, you can do the same thing by making a little template class with a pointer and a string (or a void * and a enum/type field)
mysillypointer <thing*> msp(&something, "something");


The underlying question is key. This could be anything from a nifty debugging tool to a 'just because I can' to a total lack of understanding of pointers. If you can explain what you really are trying to accomplish, you may get a better answer than just mechanical what-ifs that could do sorta kinda what you want.
Last edited on
Topic archived. No new replies allowed.