Is there a way for a compound literal to have a variable length in c99?

I know that arrays with lengths determined at runtime are possible by declaring an array usually:

char buf[len]; 

and I know that I can declare an array as a composite liter and assign it to a halfway pointer:

 char *buf; .... buf = (char[5]) {0}; 

However, combining the two does not work (not allowed by the standard).

My question is: is there a way to achieve the effect of the following code? (note len )

 char *buf; .... buf = (char[len]) {0}; 

Thanks.

+4
source share
1 answer

Language explicitly prohibits this

6.5.2.5 Compound literals

Limitations

1 The type name should indicate the type of the object or an array of unknown size, but not the type of the array of variable length.

If you need something like this, you will have to use a VLA object with a name, not a compilation literal. However, note that VLA types do not accept initializers, which means you cannot do this.

 char buf[len] = { 0 }; // ERROR for non-constant `len` 

(I have no idea what the rationale for this restriction is.)

So, in addition to using the named VLA object, you will have to come up with some way to nullify it, for example, a memset or an explicit loop.

+7
source

All Articles