Hacker News new | ask | show | jobs
by fractalb 857 days ago
Thanks for the link. As I understood it, it's just the support for the syntax that is mandatory.

> Variable length arrays with automatic storage duration are a conditional feature that implementations need not support

1 comments

The syntax and also the semantics. For instance, you can take the sizeof() a variably-modified type, or the offsetof() one of its fields, and the compiler has to do all the layout calculations implied by the type declaration at runtime. These features are partially what motivated the mandatory support. The only part that is still optional is using such types by value as stack variables (i.e., variables with automatic storage duration).
How do you create a variable array on the heap?

confused

With `malloc`, and converting the pointer to the correct type.

    void function(int n) {
      int (*arr)[n] = malloc(sizeof(*arr));
    }
wow, that's wild
That is exactly how you create any other type of object on the heap.
Snarky or just know a lot? It changes quite a bit how the compiler works. It has to know to make sure malloc gets the array element size argument multiplied in runtime by n. To a mere user it broke my mental shorthand of how a C compiler works.