Nicholas Dapprich
Nicholas Dapprich

Reputation: 7

Defining an array of structs

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.

Upvotes: 0

Views: 248

Answers (1)

J Livengood
J Livengood

Reputation: 2738

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

Upvotes: 4

Related Questions