Variable with char[] name

后端 未结 3 383
星月不相逢
星月不相逢 2021-01-24 07:15

How can I make variable in C with name specified in char table?

something like:

char name[];
gets(name[]);
int name[] = 0;

I hope you k

相关标签:
3条回答
  • 2021-01-24 07:31

    C, unlike scripting languages ala Python, or Ruby which you may be used to, is compiled not interpreted. At runtime, C does not have a look up table of variable names like the aforementioned scripting languages, this information is thrown away at compile time and thus, any name that is calculated at run-time cannot be turned into an address.

    Ultimately, as you describe it this is impossible in compiled languages. However, we do have an alternative, found in Collections such as vectors and HashMaps which store naming information at run-time, allowing us to access it. Again, unfortunately, C does not have any native implementations of these, but there are some around.

    0 讨论(0)
  • 2021-01-24 07:42

    You can't. At least not with the vanilla C language features. But remember, C has pointers which sometimes can do something similar.

    If pointers aren't what you need, you will have to implement a hash map. Higher level programming languages have them built in, but C doesn't.

    You could find a library, but if you are doing this for learning, I would recomend implimenting it yourself.

    0 讨论(0)
  • 2021-01-24 07:45

    This might be what you want. C does have a lookup table in the form of the preprocessor table where you define keywords and the text that goes with them, which are added at compilation time. So you could pass a name or whatever you want as an arg to the program during compilation and if you code it right, it will affix that name during the preprocessor portion of the compilation phase to your variable. Preprocesor phase is what looks at your #include at the top, as well as things such as #ifndef...#def, #if...#endif and so forth, C preprocessor example

    0 讨论(0)
提交回复
热议问题