0

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?

Gizmo
  • 1,990
  • 1
  • 24
  • 50
  • 5
    C99 added Variable Length Arrays so this is fine – Sami Kuhmonen Apr 09 '18 at 08:20
  • 3
    Oh that explains it, I didn't know the wording to search for, "variable" didn't come to my mind :) now I can find more information on this, thanks! – Gizmo Apr 09 '18 at 08:22
  • 1
    that's what duplicates are for. For people not knowing the terminology. All right in that case. – Jean-François Fabre Apr 09 '18 at 08:27
  • 1
    The answer that is used for the "duplicated" state describes the difference between heap and stack data. But it doesn't answer this question: `allocate an array by using square brackets, how does this work?` – harper Apr 09 '18 at 10:50

0 Answers0