2

I'm wondering for a solution to the below problem. Please help.

Problem:

struct s{
int a;
int b;
}st;

I want a function to initialize the values at runtime. The problem is that I want to make it generic, so I want to pass the member name as input to the function and get it initialized.

fun_init(char* mem, int val)
{
  // Find offset of the member variable in struct 'st'
  // Assign the value
}

One straight solution is to use string comparision on the member name. But if I happen to add some extra variables at a later time, I'll have to modify the function, which I don't want. Hope I was able to frame the ques clearly.

Thanks

hivert
  • 10,579
  • 3
  • 31
  • 56
ssin
  • 25
  • 8
  • 3
    C names don't exist at run-time. The compiled code doesn't need them. – rici Nov 28 '13 at 06:19
  • Use a `union` perhaps... – Fiddling Bits Nov 28 '13 at 06:21
  • If you only need this for one or two structures, you could use a code generator to set up the appropriate data structures or generate suitable code for accessing the fields. Of course this has the usual issues associated with code generators. – creichen Nov 28 '13 at 07:44

3 Answers3

2

C does not provide a way to find a symbol by name. See this thread for more information.

The simplest solution here is to use an associative array.

Read this thread if you need to mix value-types. (In your example, all value types are int, so you might not need this.)

Community
  • 1
  • 1
Domi
  • 22,151
  • 15
  • 92
  • 122
1
void fun_init(int *storage, int val) {
    *storage = val;
}
void something_else(void) {
    struct s {
        int a;
        int b;
    } st;
    fun_init(&st.a, 42);
}

However, if you need to dynamically determine the key name, you are doing something wrong. If you need to store key/value pairs, perhaps you would be interested in the hashtable.

Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
0

I'm guessing you want to initialize struct from either user input or persistency.

A solution involves creating an associative array as mentioned by @Domi.

The array is filled with key/value pairs such as (const char*, unsigned). The key is the name of struct member and the value is the offset from the start of the struct. Each struct will need to have a function that initializes the above array. You can get an offset to a member via the offsetof macro.

This will NOT work with structs that have bit fields (sub byte named members).

egur
  • 7,830
  • 2
  • 27
  • 47