Thread: dynamic array of structures

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    2

    dynamic array of structures

    I am doing exercises from a book and it asks that I, "use _new_ to allocate an array [of structures]," I have done it this way:

    Code:
    struct CandyBar	// define CandyBar structure
    {
      char name [20];
      float weight;
      unsigned int calories;
    };
    
    int main()
    {
      CandyBar * pEaster;	// make pointer to Candy bar type
      pEaster = new CandyBar[3]; //allocate mem for 3 CandyBar's
      delete [] pEaster; 	// free memory
      return 0;
    }
    But then I can't figure out how to assign values to the structures' elements. Any help would be greatly appreciated.

    -cjam

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Treat pEaster as an array:
    Code:
    pEaster[0].calories = 100;
    strcpy(pEaster[0].name,"Twix");
    pEaster[0].weight = 10.5f;
    And so on for all the others...
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    2

    Cool

    THANK YOU!!!! That worked and I understand now....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 02:04 AM
  2. array of structures
    By tish in forum C Programming
    Replies: 9
    Last Post: 04-05-2009, 03:17 AM
  3. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  4. Filling an Array of Structures
    By Zildjian in forum C Programming
    Replies: 5
    Last Post: 11-12-2003, 05:54 PM