Advertisement

Creating a Dynamic Array of Structures

Started by October 05, 2002 01:03 AM
1 comment, last by Tyler_Durden 21 years, 11 months ago
If creating a dynamic array with the new operator works like this: int * pt = new int[10]; and creating dynamic structures works like this: guitar * ps = new guitar; how do I create a dynamic array of structures? Everytime I try the following code, I get a compiler error. guitar * pn = new guitar[3]; Also, how do I initialize structure members allocated with new? Augusto Raffaelli
quote: Original post by Tyler_Durden
how do I create a dynamic array of structures? Everytime I try the following code, I get a compiler error.
guitar * pn = new guitar[3];

What is the exact error - that code should compile, assuming guitar is a defined struct or class.

quote:
Also, how do I initialize structure members allocated with new?

You have to loop through them after they are created, or resort to "placement new" (which is a little more advanced C++)

- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Advertisement
quote: Original post by Tyler_Durden
guitar * ps = new guitar;
guitar * pn = new guitar[3];

Both these examples would require a default constructor, if no default constructor exist then this will fail to compile. If you have created your own constructor that takes some parameters the default constructor will be removed and you need to write it yourself. See example below:

  // Struct with a default/empty (compiler generated)constructor.struct A{   int miValue;};// Struct without a default/empty (compiler generated)// constructor but with a constructor that takes an argument.// The explicit constructor that takes an argument overrides// the compiler generated one.struct B{   B(int iValue);   int miValue;};// Struct both with a default/empty constructor and a// constructor that takes an argument.struct C{   C();   C(int iValue);   int miValue;};  
Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]

This topic is closed to new replies.

Advertisement