C99 Variable Length Arrays

I just discovered today that you can have variable length arrays in C99:

#include
#include 

int main(int argc, char **argv) {
        int len;

        len = strlen(argv[0]);

        char line[len+1];
        printf("%d\n", sizeof(line));
}

Here’s what you get when compiling this:


[12:30:39 athena] tmp> gcc -pedantic -o test test.c
test.c: In function ‘main’:
test.c:9: warning: ISO C90 forbids variable-size array ‘line’
test.c:9: warning: ISO C90 forbids mixed declarations and code
[12:31:02 athena] tmp> gcc -std=c99 -pedantic -o test test.c
[12:34:44 athena] tmp> ./test
7

I’ve verified in the C99 spec that this is actually legal. This is rocking good news to me, and I’m going to start using it all over.

Discussion Area - Leave a Comment