-4

I'm expecting something like below.

int genVar001, genVar002, genVar003;
int adrgenVar, status;
char strvariable[] =  "genVar001";

status = somefunction(&strvariable, adrgenVar);

Where 'adrgenVar' will have the address of genVar001.! If the variable is not available the status should return error.

Why it is required: for manipulation of the values in the runtime (via keyboard or files).

Lookup table will not help me because it would increase the job; maintain the table if anything new is added.

Edit: I'm working with PLCs, Here is the library which will allow me to do so. Function: PV_xgetadr.

  • See [this SO post](http://stackoverflow.com/questions/4384359/quick-way-to-implement-dictionary-in-c) for some answers on how to implement a dictionary in C. In case you don't know, dictionaries generally have a list of keys with associated values. I find it quite ideal for modifying variables using a string identifier during runtime. – Arc676 Dec 30 '15 at 07:09
  • 7
    C doesn't have any built-in introspection functions like this. There's no way to find a variable from its name. – Barmar Dec 30 '15 at 07:09
  • 2
    Do you know an `int` is not guranteed to be able to hold an _address_? – Sourav Ghosh Dec 30 '15 at 07:09
  • 1
    @Barmar: Well, one certainly could write code which parses the symbol table (presuming it has not been stripped) and find the variable somehow. But you can also shoot your foot right before a marathon. – too honest for this site Dec 30 '15 at 07:11
  • Nothing in the C language allows that. You will have to resort to platform-specific code. – n. m. could be an AI Dec 30 '15 at 07:14
  • If you want a standard way, you need to bite the bullet, and accept the need to "increase the job" and then maintain the table. The only solution is to implement a lookup table. Even if you are willing to accept a non-standard way, accessing debugging information in executables (apart from being system specific) is not for the faint hearted or lazy. – Peter Dec 30 '15 at 08:38

1 Answers1

0

C doesn't have any sort of introspection capabilities in the standard, there's no way to do what you're aiming for in a portable manner. And the non-portable manners (like using the executable's debug info or symbol table) would be a terrible idea.

But that doesn't mean there's no solution. Judging by your variable names, what you should be doing is:

int genVar[3];

Then you can dynamically index into that array at runtime. If that's not flexible enough, use a linked list or a hash map - there are quite a few implementations of those for C available (none in the standard though).

Mat
  • 202,337
  • 40
  • 393
  • 406