Thanks matsp. Very good idea.
I have made some syntax changes to your program and it works very good. Really a good idea.
Code:
#include <stdio.h>
#include <stdlib.h>
#define ADD_VAR(t, x) add_var(#t, #x, &x)
#define REMOVE_VAR(x) remove_var(#x)
int total = 0;
typedef struct {
char *type_list;
char *name_list;
void *addr_list;
} store_list;
store_list *store = NULL;
void add_var(const char *type, const char *name, void *addr)
{
total++;
store = realloc(store, total * sizeof(store_list));
/* Store type, name and addr in some sort of stack/list/array/etc. */
store[total-1].type_list = type;
store[total-1].name_list = name;
store[total-1].addr_list = (int *) addr;
}
void remove_var(const char *name)
{
/* // remove the last added variable of that name. */
}
const char *get_fmt(const char *type)
{
const static struct {
char *type;
char *fmt;
} table[] =
{
{ "int", "%d" },
{ "char *", "%s" },
{ NULL, NULL }
};
int i;
for(i = 0; table[i].type; i++)
{
if(strcmp(type, table[i].type) == 0)
return table[i].fmt;
}
return NULL;
}
void print_var(const char *name)
{
int i = 0;
store_list *found;
found = NULL;
/* Find name in list. */
for (i=0; i<total; i++)
{
if (strcmp(store[i].name_list, name) == 0)
{
found = &store[i];
}
}
if (found)
{
const char *fmt = get_fmt(found->type_list);
char buffer[100];
if (!fmt)
printf("Unknown format %s\n", found->type_list);
else
{
sprintf(buffer, "%s = %s\n", name, fmt);
if (strcmp(fmt, "%d") == 0)
{
printf(buffer, *(int *)found->addr_list);
}
else if (strcmp(fmt, "%s") == 0)
{
printf(buffer, (char *)found->addr_list);
}
}
}
else
{
printf("Could not find variable\n");
}
}
int main()
{
int x = 8;
int y = 7;
char str[20] = "foo";
char name[20];;
ADD_VAR(char *, str);
ADD_VAR(int, x);
ADD_VAR(int, y);
scanf("%s", name);
print_var(name);
/*
REMOVE_VAR(str);
REMOVE_VAR(y);
REMOVE_VAR(x);
*/
}