CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2009
    Posts
    1

    Question Dynamic Array and Structures

    #include <cstdlib>
    #include <iostream>
    #include <cstring>

    using namespace std;

    struct candyBar
    {
    string strCandyBarName;
    double doubleWeightCandyBar;
    int intNumberCalories;
    };

    int main(int argc, char *argv[])
    {
    candyBar * pSnack = new candyBar [3];

    pSnack[0] = {"Mocha Munch", 2.3, 350}; // doesnt compile...
    // looking for clean way to define a dynamic array using a structure
    // without using pSnack[0].strCandyBarName -> "Munch";
    // any help making it cleaner???

    delete [] pSnack;
    system("PAUSE");
    return EXIT_SUCCESS;
    }

  2. #2
    Join Date
    May 2007
    Posts
    811

    Re: Dynamic Array and Structures

    Code:
    #include <string>
    #include <vector>
    
    struct candyBar
    {
       candyBar() : doubleWeightCandyBar(0), intNumberCalories(0) 
       {}
    
       candyBar(const std::string& name, double weight, int calories)
       : strCandyBarName(name)
       , doubleWeightCandyBar(weight)
       , intNumberCalories(calories)
       {}
    
       std::string strCandyBarName;
       double doubleWeightCandyBar;
       int intNumberCalories;
    };
    
    int main(int argc, char *argv[])
    {
       std::vector<candyBar> snacks;
    
       snacks.push_back(candyBar("Mocha Munch", 2.3, 350));
    }
    No manual memory management, no new, no delete. It's all handled by stl library. When you use C++, use C++, it will make much easier.

    Here and here are good start for vector. Rest is left as an exercise for the reader.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured