Can you initialize a dynamically-sized variable-length array to zero?

85 Views Asked by At

In the book 21st Century C Tips From the New School. On page 171 it says,

Now for the sad part: let us say that you have a variable-length array (i.e., one whose length is set by a runtime variable). The only way to zero it out is via memset :

int main(){
  int length=20;
  int ll[length];
  memset(ll, 0, 20*sizeof(int));
}

So it goes. 1.

The footnote for that section reads,

  1. You can blame ISO C standard §6.7.8(3) for this, because it insists that variable length arrays can’t be initialized. I say the compiler should be able to work it out.

I don't see this mentioned anywhere though in the seminal answers on this matter on StackOverflow which seem to suggest that this would work,

int main(){
  int length=20;
  int ll[length] = {0};
}

Is this the proper reading of the ISO C 2011 Standard?

0

There are 0 best solutions below