Getting Variable dynamic in c
I have one requirement in C.
char abc[]="hello";
char hello[]="world";
Using abc whether we can get the hello vari开发者_运维百科able's value in C. I know it is possible in some of the languages like Perl, Php, Bash,.,
Is it possible in C?
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.
No, this is not possible in C without providing a string lookup table of some sort that could link variables with their names.
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.
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.
It is not possible in C. It can be done in java by reflection in some cases.
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.
精彩评论