There are a few ways you could go.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
// All the values are the same type
struct Pair {
const char *name;
int value;
};
struct Pair example[3] = {
{ "ab", 0 },
{ "ba", 0 },
{ "ca", 0 },
};
void assign(struct Pair data[], size_t len, const char *name, int value) {
for ( size_t i = 0 ; i < len ; i++ ) {
if ( strcmp(data[i].name, name) == 0 ) {
data[i].value = value;
}
}
}
// All the values have different types
struct Pair2 {
const char *name;
int offset;
enum {
T_INT,
T_DOUBLE,
T_CHAR,
} type;
};
// Your data, with heterogenous types
struct Data {
int ab;
double ba;
char ca;
};
struct Pair2 map[3] = {
{ "ab", offsetof(struct Data,ab), T_INT },
{ "ba", offsetof(struct Data,ba), T_DOUBLE },
{ "ca", offsetof(struct Data,ca), T_CHAR },
};
void assign2(struct Pair2 map[], size_t len, const char *name, struct Data *instance, int value) {
for ( size_t i = 0 ; i < len ; i++ ) {
if ( strcmp(map[i].name, name) == 0 ) {
switch ( map[i].type ) {
case T_INT:
{
int *p = (int*)((char*)instance + map[i].offset);
*p = value;
break;
}
case T_DOUBLE:
{
double *p = (double*)((char*)instance + map[i].offset);
*p = value;
break;
}
case T_CHAR:
{
char *p = (char*)((char*)instance + map[i].offset);
*p = value;
break;
}
}
}
}
}
int main ( ) {
assign( example, 3, "ba", 42);
struct Data instance;
assign2( map, 3, "ba", &instance, 42);
printf("%d %f\n", example[1].value, instance.ba);
}