Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct "Incomplete type is not allowed"

Tags:

c++

arrays

struct

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.

like image 330
Hugius Avatar asked Jan 30 '16 20:01

Hugius


2 Answers

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

like image 117
Michael Dubé Avatar answered Nov 19 '22 03:11

Michael Dubé


 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.

like image 1
Sir Mate Avatar answered Nov 19 '22 02:11

Sir Mate