3

I have this struct:

struct Foo {
    int a;
    int* b;
};

Then I'm creating an instance for it like this:

int x [] = { 5, 6 };
Foo y = { 2, x };

But, I'd like to create the x array inline, maybe something like this:

struct Foo y = { 2, (int[]) { 5, 6 } };

But the example above do not work... How can I achieve this?

--------- EDIT:

I'm getting this error from intellisense:

cast to incomplete array type "int []" is not allowed

Build error:

Error C4576 a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax

I'm using Visual Studio 2015 (v140).

João Paulo
  • 6,300
  • 4
  • 51
  • 80
  • 1
    If you're "creating an instance" like `Foo y = { 2, x };` then there's something missing that you don't show us. There's no type `Foo`. Please create a proper [mcve] to show us. And don't forget to tell us the full and complete error message you get. – Some programmer dude Jan 29 '19 at 12:02
  • 2
    ___Please do not change the question body once an answer is posted. You can always append to it, but changing it completely makes the answer(s) invalid.___ – Sourav Ghosh Jan 29 '19 at 12:07
  • 1
    You can't `free` the `b` member, because the pointer value was not obtained from `malloc` etc. – Weather Vane Jan 29 '19 at 12:11

1 Answers1

7

In your case, Foo is not a type.

Try

struct Foo y = { 2, (int[]) { 5, 6 } };

It works as expected


Edit:

You only need to free() the memory programatically which you allocate using the allocator function (malloc() and family). The memory which is not returned by an allocator function, need not be free()-d by the programmer.


Edit 1:

Regarding the C4567, see this

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261