How to run time initialize array of structures

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jeevan83
    New Member
    • Aug 2014
    • 9

    How to run time initialize array of structures

    Hi, guys, I somewhere read "You cannot initialize a structure like that at run time."
    example:
    Code:
    struct item_info
    {
          char itemname[15];
          int quantity;
          float retail;
          float wholesale;
     }item[NOOFITEM];
    int main()
    {
           item[0]={"rice",10,40,30};
           item[1]={"sugar",10,40,30};
           item[2]={"soap",10,40,30};
    }
    But if you want to assign values at run time then you have to do it manually like:
    Code:
    strcpy(item[0].itemname, "rice");
    item[0].quantity = 10;
    item[0].retail = 40;
    item[0].wholesale = 30;
    i tried in internet but am unable to know the differences. I want to know the difference between those two in terms of run time and compile time.
    Please explain me also the below one. Is this run time or compile time? How does we actually decide which is run time and which is compile time!
    Code:
    struct item_info
    {
          char itemname[15];
          int quantity;
          float retail;
          float wholesale;
          //int quatityonorder;
    }item[NOOFITEM] =
    {
        {"rice",10,40,30},
        {"sugar",10,40,30},
        {"soap",10,40,30}
    };
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    If the array exists, then you have to assign values individually.

    Code:
    item_info array[15];
    //At this point the array exists so you need assignment
    strcpy(array[0].itemname,"rice");
    But here the array does not exist. Now you can initialize the elements:

    Code:
    struct item_info
    {
          char itemname[15];
          int quantity;
          float retail;
          float wholesale;
          //int quatityonorder;
    }item[NOOFITEM] =
    {
        {"rice",10,40,30},
        {"sugar",10,40,30},
        {"soap",10,40,30}
    };
    This is always a question on a job interview.

    Code:
    int i = 5;
    i does not exist. This is initialization.

    Code:
    int i;
        i = 5;
    i exists. This is assignment.

    Comment

    • Jeevan83
      New Member
      • Aug 2014
      • 9

      #3
      Hi bro, here NOOFITEM is a macro and will be replaced by 12, sorry I didnt post it! If its 12 then it's an array right?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        That is correct. It will be an array of NOOFITEM elements.

        Comment

        Working...