GrandeKnight
GrandeKnight

Reputation: 35

How to assign anonymous VLA to pointer?

Currently I am assigning a VLA to a pointer as follows

struct Foo {
    int* array;
};

int array[size];

struct Foo foo = {
    .array = array;
};

Is it possible to replace this with an "anonymous" array?

What I tried:

struct Foo foo = {
    .array = (int[size]) {} // fatal error: variable-sized object may not be initialized
};

What I was hoping for:

struct Foo foo = {
    .array = int[size]; // something similar to this if I am making any sense.
};

PS: I am not looking for dynamic memory allocation (malloc/calloc).

Upvotes: 2

Views: 139

Answers (3)

Lundin
Lundin

Reputation: 215090

Given the "must be allocated on the stack and array must be small", one obvious solution would be this:

struct Foo {
    int array [MAX];
    size_t size;
};

That is, always allocate some 256 bytes but keep track of how much of that is used to store data.

As a bonus, you get rid of one level of indirection by placing the array directly in the struct which might give an itty bit of performance increase.

Upvotes: 1

ikegami
ikegami

Reputation: 386621

Is it possible to replace this with an "anonymous" array?

No.

Specifically, you are asking how to create an anonymous variable-length array. C does not support those.

Of compound literals ((){}), the C standard says:

C17 §6.5.2.5 ¶1 The type name shall specify a complete object type or an array of unknown size, but not a variable length array type.

Your only options are the nonstandard alloca/_alloca.

Upvotes: 3

John Bollinger
John Bollinger

Reputation: 181689

Is it possible to replace this with an "anonymous" array?

No, not if the wanted size cannot be given in the form of an integer constant expression, unless you're willing to use an allocation function.

Of objects recognized by C language semantics, only literals, dynamically allocated objects, and certain structure and union members are without any name anywhere. Compound literals of VLA type are expressly forbidden (they violate a language constraint). Structures and unions cannot have members of VLA type, so you can't get one through a compound literal of such a type, either. The "certain structure and union members" I referred to are for completeness only; they have structure or union type themselves, so they are no help. You have ruled out dynamic memory allocation, so there's nothing left.

If there is an upper bound on the size you want to support (and in practice there is, because stack space is pretty limited) then you could use an array of that size instead.

Upvotes: 2

Related Questions