0

I have this code below which creates an array of variable size that compiles and runs fine on my mac.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int w = 100;
    int ar[w];
    ar[2] = 42;
    printf("%d\n",ar[2]);
}

I thought variable sized arrays were not permitted in C. what is happening here exactly? How is memory being managed? Does the memory get dynamically allocated at run time? Thanks

5
  • Research variable length array. Commented May 19, 2020 at 21:41
  • @mathew There is used memory with the automatic storage duration not the memory with the allocated storage duration. Commented May 19, 2020 at 21:43
  • They were never permitted in MS VC despite the fact they were mandatory. They are now optional. Even if supported your code has undefined behaviour because you access an array element that was not initialised. It is a local array, so follows the usual rules for local (automatic) variables. Commented May 19, 2020 at 21:43
  • Runs fine on your mac? By outputting -42? Commented May 19, 2020 at 21:48
  • sorry, I should have made it not have undefined behaviour. This wasn't really the point I was trying to get at though, I just wanted to point out that it compiled even though it had variable length. I realize this was a confusing thing to do so I fixed the question. Commented May 19, 2020 at 23:21

1 Answer 1

1

What's happening here is that variable-length arrays are a relatively new feature, only first appearing in the C standard in 1999. C standards are not adopted as quickly in the C world as JavaScript and Python; I can remember the excitement in 2007 or so when my workflow was finally able to include VLAs.

To add insult to injury, while C++ is a mostly-superset of C, VLAs are not supported, meaning that the common use-case of folks compiling C code with C++ compilers will not work.

There was enough pushback from the compiler vendors that the standard eventually (C11) made VLAs optional, mandating the feature-test macro __STDC_NO_VLA__ instead.

(see ISO stadndard 9899:2011 Programming Languages - C, section 6.7.6.2 4)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.