What’s the point of VLA anyway?

For reasons that are not entirely clear to me, almost every time the topic of C99 VLA pops up in a discussion, people start talking predominantly about the possibility of declaring run-time-sized arrays as local objects (i.e. creating them “on the stack”). This is rather surprising and misleading, since this facet of VLA functionality – … Read more

Is there any overhead for using variable-length arrays?

VLA does have some overhead (compared to “ordinary” named compile-time-sized array). Firstly, it has run-time length and yet the language provides you with means to obtain the actual size of the array at run-time (using sizeof). This immediately means that the actual size of the array has to be stored somewhere. This results in some … Read more

How does the compiler allocate memory without knowing the size at compile time?

This is not a “static memory allocation”. Your array k is a Variable Length Array (VLA), which means that memory for this array is allocated at run time. The size will be determined by the run-time value of n. The language specification does not dictate any specific allocation mechanism, but in a typical implementation your … Read more

Difference between array type and array allocated with malloc

There are several different pieces at play here. The first is the difference between declaring an array as int array[n]; and int* array = malloc(n * sizeof(int)); In the first version, you are declaring an object with automatic storage duration. This means that the array lives only as long as the function that calls it … Read more

Can’t understand this way to calculate the square of a number

Obviously a hack… but a way of squaring a number without using the * operator (this was a coding contest requirement). (&a)[n] is equivalent to a pointer to int at location (a + sizeof(a[n])*n) and thus the entire expression is (&a)[n] -a = (a + sizeof(a[n])*n -a) /sizeof(int) = sizeof(a[n])*n / sizeof(int) = sizeof(int) * … Read more

C compile error: “Variable-sized object may not be initialized”

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length … Read more