initialize struct char pointer array in struct

Nov 28, 2014 at 9:00am
Im trying to store data in a struct to be able to read it latter
have problems initializing this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
struct FoodAndDrink
{
	struct Food
	{
		char* CannedGoods[2] = {
			"Canned Spaghetti",
			"Canned Tuna",
		};
		char* DryFood[2] = {
			"Rice",
			"Box of Cereal"
		};
		char* Fruits[5] = {
			"Apple",
			"Banana",
			"Kiwi",
			"Orange",
			"Tomato",
		};
	}_Food;

	struct Drinks
	{
		char* Waterbottle[1] = {
			"Waterbottle"
		};
		char* SodaCan[3] = {
			"Coke",
			"Pepsi",
			"Sprite",
		};
	}_Drinks;
};
Last edited on Nov 28, 2014 at 9:00am
Nov 28, 2014 at 10:39am
Describe your problem please.
Nov 28, 2014 at 11:28am
error C2536: 'FoodAndDrink::Food::FoodAndDrink::Food::CannedGoods' : cannot specify explicit initializer for arrays
Nov 28, 2014 at 11:59am
Your code fragment displays a type definition. A type is not associated with memory, so its impossible to assign any values (with the exception of static constant attributes).

Types may be instantiated as variables or constants wich may be initialized at compile- or at runtime. (see cplusplus-tutorial).
Nov 28, 2014 at 12:05pm
So there is no way to have it all defined inside a struct to be neat?
Nov 28, 2014 at 12:13pm
1) Proper type for string literals is const char*
2) Turn on C++11 suppor in your compiler.

And mainly: why do you need nonstatic arrays inside structs? Woldn't his be enough:
1
2
3
4
5
6
7
8
9
namespace FoodAndDrink
{
	namespace Food
	{
		const char* const CannedGoods[2] = {
			"Canned Spaghetti",
			"Canned Tuna",
		};
//... 
Nov 28, 2014 at 12:15pm
Define a constructor of FoodAndDrink. It may run initialization code on each new instantiation.
Nov 28, 2014 at 12:15pm
Thanks MiiNiPaa i didnt even think about using namespace
Topic archived. No new replies allowed.