Dynamic structure array inside of a structure?

Question:
How can I create a Structure that has a Dynamic Structure (array) inside of it using only the <new> and <iostream> libraries?

example:
1
2
3
4
5
6
7
8
9
struct fruit{
char name[100]
int seeds;
};
struct container{
fruit non_poisonous //unknown until later into the program how many fruit are poisonous must be declared as a dynamically arrayed structure
};




Please provide examples.(or full sample code)

I'm a little new to using <new> =).
Last edited on
Easiest would be to use a vector but that was not allowed :(

In container you store a pointer fruit*.
1
2
3
struct container{
	fruit* non_poisonous;
};


When you know how many fruits you want to store you can use the new keyword to create an array.
1
2
container c;
c.non_poisonous = new fruit[N]; // N is the number of fruits in the array 


You can now use non_poisonous similar to the array.

1
2
3
c.non_poisonous[0] .seeds = 5;
std::cout << c.non_poisonous[5].name;
...


When you don't going to use the array any more you can call delete c.non_poisonous to free the allocated memory.
THANK YOU!
You saved me from hours of endless trial and error.
I could've done it without structures inside structures, however there's so much in the actual program that everything would've taken ages to implement and even longer to actually use.
Topic archived. No new replies allowed.