0

I have data that I would like to assign to an array of structs.

Kind of like how you can do this:

int foo [5] = { 16, 2, 77, 40, 12071 };

Why doesn't this work for something like this:

Defining the structure type.

struct Creature {
  std::string name;
  int x, y;
};

Then for the array.

const Creature list[NUM_CREATURES] = {
  name = "Walrus";
  x = 2; y = 6;,
  name = "Sardine";
  x = 3; y = 1;,
  name = "Seahorse";
  x = 4; y = 2;,
  name = "Jellyfish";
  x = 1; y = 10;,
  name = Dolphin";
  x = 8; y = 4;
  }

I have all of this located in the header file. I am defining this list as a constant as I will use these to fill another larger array then sorting the array by the size of the x and y dimensions.

3
  • Note that solutions that can be used in c are probably not valid in c++ so I removed the c tag. Commented Mar 21, 2018 at 0:19
  • @Slava I knew the syntax was wrong, that's why I asked the question. Thank you for your input. Commented Mar 21, 2018 at 0:44
  • @NicholasDapprich you should formulate your question properly. For example: "how can I initialize such structure, I tried this way and it does not work" would have very different response. Commented Mar 21, 2018 at 0:52

1 Answer 1

4

You have to initialize each struct in the initializer.

const Creature list[NUM_CREATURES] = {
  { "Walrus", 2, 6 },
  { "Sardine", 3, 1 },
  ...
}

With uniform initialization you don't need to do (and cant do) name=/x=/ect

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, makes sense. The different types threw me off.
It's not that you "don't need" it's that you "can't use" in C++.
C++20 may add a basic version of designated initializers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.