dynamic creation of structure defination

Discussion in 'C' started by sharak16, Jan 20, 2012.

  1. sharak16

    sharak16 New Member

    Joined:
    Jan 20, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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..
     
  2. neo_vi

    neo_vi Member

    Joined:
    Feb 1, 2008
    Messages:
    720
    Likes Received:
    16
    Trophy Points:
    18
    Occupation:
    Software engineer
    Location:
    Earth
    Home Page:
    http://computertipaday.blogspot.com
    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.
     
  3. virxen

    virxen Active Member

    Joined:
    Nov 24, 2009
    Messages:
    387
    Likes Received:
    90
    Trophy Points:
    28
    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.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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;
    }
    }
    
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice