6

I know that arrays with lengths determined at runtime are possible by declaring the array normally:

char buf[len];

and I know that I can declare an array as a compound litral and assign it to a pointer midway:

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

However, combining the two doesn't work (is not allowed by the standard).

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

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

Thank you.

seininn
  • 411
  • 5
  • 13

1 Answers1

9

The language explicitly prohibits this

6.5.2.5 Compound literals

Constraints

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

If you need something like this, you'd have to use a named VLA object instead of compund literal. However, note that VLA types do not accept initializers, meaning that you can't do this

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

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

So, in addition to using a named VLA object you'll have to come up with some way to zero it out, like a memset or an explicit cycle.

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Thanks for the quick response (and const. edits ;) ). However, I'm aware that the standard prohibits it. I'm trying to avoid littering my code with temp variables and was hoping that there is something with a syntax that is as convenient as compound literals. – seininn Jan 27 '13 at 18:29
  • 4
    Thought so, it's a shame since variable compound literals should technically be possible because VLAs are. Hopefully the next standard.. – seininn Jan 27 '13 at 18:36
  • @seininn. I agree with your use for temporaries. I think the ideal construct for this use would be just the first part of the compound literal. Simply (float [n]){} with the empty initializer because all we need is space and auto-initializing a variable length array is probably of limited utility anyway. It conflicts with the gcc {} extension but zero init wouldn't be a horrible deal either. – Samuel Danielson Feb 09 '16 at 00:48