I was quite surprised to find that the following code does work as one (beginner) would expect (Well I expected it to either fail to compile or segfault):
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int count = rand() % 1024 + 2;
int arr[count];
arr[count-1] = 3;
for(int i = 0; i < count; ++i)
{
arr[i] = i * 3;
}
printf("%d %d %d", count - 1, arr[0], arr[count-1]);
return 0;
}
To my surprise this compiles, and works.
I did not know it is possible to dynamically allocate an array by using square brackets, how does this work? I expected any kind of error stating that dynamic allocation using []
isn't allowed or possible in C.
How does this work?