-1

If I have a struct like this

struct my_struct
{
    float a, b;
};

Is there a way to declare an object by doing so?

my_struct[10][10] my_struct_inst;

If this is allowed, could anyone teach me how to understand this? Or what's the concept of this code?

So many thanks in advance.

yuhow5566
  • 555
  • 4
  • 20
  • 2
    What resource are you using to learn C++? What does it say about array declarations and their syntax? – Some programmer dude Apr 11 '22 at 11:13
  • And you can have an array of any type, including other arrays. So an array of arrays (or `my_struct`) is perfectly fine and value. Though I would rather recommend `std::array` for arrays with a size that is known and fixed at compile-time. – Some programmer dude Apr 11 '22 at 11:14
  • "array of struct?" yes. What makes you doubt that this is an (2d) array of structs? – 463035818_is_not_an_ai Apr 11 '22 at 11:14
  • 2
    The correct syntax is `my_struct my_struct_inst[10][10];`, which any introduction to C++ arrays would tell you. I think you need one of [these](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Apr 11 '22 at 11:22
  • umm thanks to all of you, I just want to know if this syntax is reasonable or not. Thanks for the answer and the guy who downvoted it – yuhow5566 Apr 11 '22 at 11:39

1 Answers1

2

Your syntax is simply wrong. Array size goes after the variable name, not the type:

my_struct my_struct_inst[10][10];

Note that the type of my_struct_inst is still my_struct[10][10], that's just the syntax for variable definitions.


With modern C++, I would consider using std::array instead, though that's not pretty either:

std::array< std:array<my_struct, 10>, 10> my_struct_inst;

This is basically same thing and equally efficient, but it also offers a bunch of nice methods, which may be useful.


To make that easier, you can define it as a type:

using my_struct_10x10 = std::array< std:array<my_struct, 10>, 10>;
my_struct_10x10 my_struct_inst;
hyde
  • 60,639
  • 21
  • 115
  • 176