5

Does anyone know what this error means and why it is occurring when I am trying to define an array inside a struct?

struct test{
    int idk[] = { 1,2,3 };
};

Why is the array idk incomplete type or something?

Thanks in advance.

Ps. I need this so I can access these arrays from the test struct.

Hugius
  • 380
  • 1
  • 5
  • 15
  • 1
    Use `int idk[3] = { 1,2,3 };` – Jakube Jan 30 '16 at 20:32
  • 3
    Most of the time, the array size can be deduced from initializer. But that doesn't work for arrays that are class members. For these, you have to spell out the size explicitly. – Igor Tandetnik Jan 30 '16 at 20:33
  • 1
    Unlike in a variable definition, the default-member-initializer of a non-static class data member isn't the only initializer that the member can have, so it's not suitable for inferring the array size. – Kerrek SB Jan 30 '16 at 20:36

2 Answers2

5

When declaring a variable in a local scope (like in a function body, for example), you can do this and the compiler will not complain, it will deduce that you mean an array of int of 3 elements.

void someFunc()
{
    int idk[] = { 1,2,3 }; // Ok, so idk is in fact a int[3];
    // Do whatever work...
}

When doing the same thing in a class or struct declaration, the compiler do not want to deduce that for you, so basically, you need to be stricter.

For a complete reason of why, you can see here (What is the reason for not being able to deduce array size from initializer-string in member variable?) among other places.

So, to make it work, you need to so this:

struct test 
{
    int idk[3] = { 1,2,3 };
};

As to why people might dislike this question, well this is kind of a mundane question and really any search in google will yield the answer. The compiler itself will back out the error, and just searching for that will most of the time find the answer for you.

Basically, this kind of question is telling the community here you did not do any research prior to asking your question.

With visual studio compiler, it creates this error: Error C2997 'test::idk': array bound cannot be deduced from an in-class initializer

Which is pretty explicit.

Mick

Community
  • 1
  • 1
Michael Dubé
  • 136
  • 1
  • 5
  • I have Visual Studio but for some reason did not I get that error. I did research, but everytime people had discussions about arrays of structs. But thanks for the explanation. – Hugius Jan 30 '16 at 20:46
1
 array bound cannot be deduced from an in-class initializer

So changing the snippet to

struct test{
int idk[3] = { 1,2,3 };

results in successful compilation.

Sir Mate
  • 75
  • 1
  • 6