简体   繁体   中英

array of variable size in c

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM