7

I'm studying for my test in C and I'm reading in a C summary I downloaded from some site. It is written that it is not allowed to write arr[i] where i is a variable. The only way to do it is with malloc.
However, I wrote the following code and it compiles without warnings and without error on valgrind:

int index = 5;
int a4[index];

a4[0] = 1;
a4[1] = 2;

int index2;
scanf("%d",&index2);
int a5[index2];
a5[0] = 1;
a5[1] = 2;

So what is the truth behind array declarations? thank you!

2
  • As a warning: I would recommend not trusting summaries of C found on the Internet too much; I recently spent a lot of time reviewing C and C++ in preparation for interviews, and found that most of the Internet "study guides" had inaccurate or misleading information in them. I'd recommend a good introductory book, with the caveat that often such books don't cover C99 features because they are less commonly implemented. Sep 28, 2010 at 16:21
  • 1
    While they're legal in C99, VLAs are extremely dangerous unless you already have a very small bound on the value of the expression to be used as the array size. They can easily lead to stack overflow (not the good kind :-) and clobbering of heap memory. Sep 28, 2010 at 17:06

1 Answer 1

16

C99 allows variable length arrays to be created on the stack. Your compiler may support this feature. This features is not available in C89.

What the summary told you was true, from a certain point of view. :-)

1
  • The variable length array makes me feel confused at first because I remember it's not supported when I used to learn C using VC6.0. Just now I find it is used on the example code of InsertionSort on Hackerrank.com. Now it's clear. Hackerrank adopts gcc4.7.3,C99 Mode, so this feature is totally supported.
    – ChandlerQ
    Jul 9, 2013 at 10:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.