Reputation: 1721
I have one requirement in C.
char abc[]="hello";
char hello[]="world";
Using abc whether we can get the hello variable's value in C. I know it is possible in some of the languages like Perl, Php, Bash,.,
Is it possible in C?
Upvotes: 3
Views: 209
Reputation: 34968
POSIX has several functions that allows you to do it, assuming variable hello
is global and isn't static:
void *handle = dlopen(NULL, RTLD_NOW);
// error handling omitted
printf("%s variable contains value %s", abc, (char *)dlsym(handle, abc));
dlsym()
return value is casted to char *
to suppress warning when using compilers that check format string for printf
-alike functions.
And you need to make sure you've specified correct compiler options, e.g. -rdynamic -ldl
in case of GCC.
Upvotes: 0
Reputation: 328604
As soon as the C compiler has figured out where to store the underlying pointers, it forgets about the name you gave it. The dynamic languages solve it with a data structure like a hash map which allows you to store the pointers (value) under a key (the name).
Another option is to read in the debug information. This is only available if you compile your code with -g
(gcc) or some other, compiler specific option. Note that the debug format is not standardized, so you'll need to figure out what your compiler uses and how to work with it.
Upvotes: 1
Reputation: 273476
It's impossible in C, unlike in more dynamic languages like Perl or Python. However, it's important to keep in mind that even in those languages this isn't recommended. I haven't seen a snippet of code putting this to a good use yet. The eval
methods available in dynamic languages are used sparingly, and not for dynamically grabbing variable names.
Upvotes: 1
Reputation: 41097
It is not possible in C. It can be done in java by reflection in some cases.
Upvotes: 0
Reputation: 4797
Yes you are right , this is possible in some other language but not in C , since abc is a container which resides in a location (for ex: 1000) and hello is one more container which resides in another location ( for ex : 2000 ) , so we have no contact between these two arrays ,
we cannot make a value ( strings ) to point some other value. so finally THIS IS NOT AT ALL POSSIBLE.
Upvotes: 2
Reputation: 13244
No, this is not possible in C without providing a string lookup table of some sort that could link variables with their names.
Upvotes: 2