user3362932 user3362932 - 1 year ago 61
C Question

Creating a certain struct at run time in c

I have an assignment for which the user will specify at run time the type of struct that they want to create.

For instance, lets say that the user inputs:

name : char[50], address: char[50] and age: int

Then my program will have to create a struct containing these 3 types of variables. Note that the user can specify as many variables as they want for the struct, only limiting them to char and int.

How should my code be in order to create a struct as specified above?

This is for c programming language only!

Answer Source

a variable have 3 fields: 1) type, 2) name, 3) address. you shuold create an array of struct containing these 3, array of this struct will be what you want

your structs may look like this:

typedef enum _Type{T_INT,T_STRING}Type;
typedef struct _var{
  Type type;
  char* name;
  union {int n; char* str;} data;

typedef struct _Struct{
  int count;
  var* array;
} Struct;

when you get the input, you need to build the Struct according to it. name : char[50], address: char[50] and age: int

Struct *s = malloc(sizeof(Struct));
s->count = 3;//count of fields in the input
s->array = malloc(s->count*sizeof(var));
//you really should do it in a loop, after parsed the input...  
  s->array[i].name = strdup(parsedname);//"name", "address", "age"
  s->array[i].type = strcmp(parsedtype,"int")?T_STRING: T_INT;
  //for string you need to alloc memory for string...
  if(s->array[i].type == T_STRING)
    s->array[i].data.str=malloc(50 /*the size you've got*/);
  //not need to alloc memory for the int

when you finish don't forget to free the mallocs:

 if(s->array[i].type == T_STRING)

You'll also need a method to fill the struct and print it, and so on...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download