Interview Questions

Can the size of an array be declared at runtime?

C Interview Questions and Answers


(Continued from previous question...)

Can the size of an array be declared at runtime?

No. In an array declaration, the size must be known at compile time. You can’t specify a size that’s known only at runtime. For example, if i is a variable, you can’t write code like this:
char array[i]; /* not valid C */
Some languages provide this latitude. C doesn’t. If it did, the stack would be more complicated, function calls would be more expensive, and programs would run a lot slower. If you know that you have an array but you won’t know until runtime how big it will be, declare a pointer to it and use malloc() or calloc() to allocate the array from the heap.

(Continued on next question...)

Other Interview Questions