开发者

Is it possible to find out the variable name, the pointer pointing to?

Is it Possible to get the name of array the pointer pointing to?

example:

 char name[20];
 char *p = name
 int door_no;
 int *q = &door_no

In the above example we are giving the base address of the array with the array name and pointer q pointing to door_no but what if, I have to know the name of the variable the array is pointing to? What is the variable name pointer q is pointing to? Is it possible? I tried and came to the conclusion that it's not possible but still I am trying to get the s开发者_Go百科olution. What you think guys? Is there any way to make it possible?


No, you can't do that. The names of variables do not even exist after your code is compiled and linked (unless you're keeping debugging information around), so you can't get at it at run time.

In C (in contrast to very dynamic languages such as JavaScript or classical Lisp), the only role of variable names is to tell the compiler/linker which declaration you're pointing at when you mention a variable in the source code. Once these connections have been made and represented in the compiler's internal data structures, there is no further use for the names (again, except for debugging and/or pretty-printing of error messages from the compiler).


Everything that Henning said before me is correct. In addition, the target of a pointer might not even have a variable name. For example, consider:

char a;
char *ptr = &a + 5;

Now ptr is pointing somewhere that doesn't have anything to do with a (and in fact might be pointing outside of the memory allocated for your program and doing anything with that pointer could cause a segmentation fault).


It is not possible to get the name of the variables p or q point to if you compile and execute the program traditionally, because one of the things the compiler does is forget the name of the variables, keeping only addresses.

Depending on what you are trying to do, you may execute the program in a non-traditional execution environment where the names are preserved. For instance,

~ $ cat t.c
main(){
 char name[20];
 char *p=name;
 int door_no;
 int *q= & door_no;
}
~ $ frama-c -val t.c
[kernel] preprocessing with "gcc -C -E -I.  t.c"
...
[value] ====== VALUES COMPUTED ======
[value] Values for function main:
          p ∈ {{ &name ;}}
          q ∈ {{ &door_no ;}}
          __retres ∈ {0; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜