Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   dynamic creation of structure defination (http://www.go4expert.com/forums/dynamic-creation-structure-defination-t27636/)

sharak16 20Jan2012 19:43

dynamic creation of structure defination
 
how can i create structure at run time.i.e structure name and data types of varibles are given by user and according to that a appropriate structure is been created.pls some one help me.i m in trouble..

neo_vi 21Jan2012 16:45

Re: dynamic creation of structure defination
 
Quote:

Originally Posted by sharak16 (Post 91463)
how can i create structure at run time.i.e structure name and data types of varibles are given by user and according to that a appropriate structure is been created.pls some one help me.i m in trouble..

Creating a structure at runtime? :crazy:
I can think of only one option. If the user passes you the data types, you can allocate so much of memory in the heap and try to make that visible as a structure to other parts of your program. But you can't create a structure as if it is statically linked in your program, AFAIK.

virxen 21Jan2012 19:49

Re: dynamic creation of structure defination
 
Quote:

Originally Posted by sharak16 (Post 91463)
how can i create structure at run time.i.e structure name and data types of varibles are given by user and according to that a appropriate structure is been created.pls some one help me.i m in trouble..

1)what language?
2)let's say you make it.How will you use it your program?
3)variables? you know from the beginning how many you have?

you could give us more information on this.It's not clear what you want to do.

xpi0t0s 22Jan2012 04:13

Re: dynamic creation of structure defination
 
You can't. Simple as that. C and C++ do not support runtime type creation (unlike, say, Javascript).

The only way is to emulate it, for example with unions, although there are other ways. Basically you will need a variable to indicate the type, and a bunch of bytes to represent the data. For example:
Code:

int types[10];
char *data[10];

types[0]=1; // let's say 1 is int
data[0]=malloc(sizeof(int));
*((int*)(data[0])=27; // let's initialise that int to 27 (not sure about that syntax
// but basically data[0] is a char*, so we cast that to int* then dereference it)

types[1]=2; // let's say 2 is a string
data[1]=malloc(strlen("Hello")+1);
strcpy(data[1],"Hello"); // let's set data[1] to "Hello"

for (int i=0; i<10; i++)
{
switch (types[i])
{
case 1: // handle an int
  printf("%d",*((int*)(data[i]));
  break;
case 2: // handle a string
  printf("%s",data[i]);
  break;
}
}



All times are GMT +5.5. The time now is 05:38.