简体   繁体   中英

Inline initialization of an array

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM