0

I played with arrays and memory and found that

int x;
scanf("%d", &x);
int arr[x];
printf("%d", sizeof(arr));

Print the size of the array. How can C know the size of the array at runtime?

Adam Katav
  • 350
  • 3
  • 10
  • from german wikipedia https://de.wikipedia.org/wiki/Variable_Length_Array : "The operator `sizeof`has to be evaluated at runtime, [...] therefore for every VLA there must be generated meta-data at runtime". So I think a VAL is internally saved something like `int* pointer` and `n count` where n is he return value of `sizeof` – RoQuOTriX Sep 18 '19 at 13:39
  • @RoQuOTriX So for every array a meta like size_t is created and sizeof() returns that? – Adam Katav Sep 18 '19 at 13:42
  • 1
    I think so, but I don't know how it is implemented internally. I only tried to translate the wikipedia article – RoQuOTriX Sep 18 '19 at 13:43
  • 1
    The language definition only mandates that VLAs are special, and that `sizeof` on a VLA has to be evaluated at runtime. *How* that's accomplished is up to the specific implementation. There has to be some kind of bookkeeping under the hood, but there are no requirements on how to do it, and there's no requirement to make any of that public. – John Bode Sep 18 '19 at 14:26
  • @JohnBode Do you happen to know how GCC does it? – Adam Katav Sep 19 '19 at 15:17
  • 1
    @AdamKatav: Not for sure - [this answer](https://stackoverflow.com/questions/21182307/how-does-gcc-implement-variable-length-arrays) seems reasonable for x86. I've never used [`alloca`](http://man7.org/linux/man-pages/man3/alloca.3.html) myself, so I can't really say if that's the usual mechanism or not. – John Bode Sep 19 '19 at 15:24

0 Answers0