0
#include <stdio.h>
#include <stdlib.h>

struct student{
 int wkTime;   
} x;

int main(void) {
struct student* john = malloc(sizeof(x));
john ->wkTime = 10;

void* emp;
emp = (char *) "wkTime";

printf("%d",john ->wkTime);
printf("%d",john -> *(emp));

return 1;
}

I would want to access the value of vaiable - wkTime not using john ->wkTime but using *emp I would like to get the value of wkTime variable of john. Essentially in the case where I would be having the variable name in form of a character pointer. I would want to use that to access the variable inside my instance of student node.

Shiva m.s
  • 27
  • 5
  • 1
    here `struct node* john ` means what? do you have any `struct node`? – Rustam Oct 01 '14 at 04:30
  • here `printf("%d",john -> *(emp));` emp is not a member of your `john` then why try to do like this..? – Rustam Oct 01 '14 at 04:32
  • `john ->wkTime` it is suggests `*(john + 0)` what can dereference your entry - `john -> *(emp)` == `*(john + *(emp))` - delirium. Moreover, that this record is not correct – Ivan Ivanovich Oct 01 '14 at 09:12

1 Answers1

4

There's no built-in way to do this in standard C. Most variable and field names don't even exist in the compiled binary, so it's impossible to do. C does not support reflection-like features in general.

If you need functionality like this, you'll have to implement it by hand. One way would be to write an accessor function that takes a pointer to the struct and the field name, and returns the value. Another option would be a table of names and field offsets/sizes.

Of course, each one of these methods requires listing out the fields by hand at least once.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159