I was reading a book when I found that array size must be given at time of declaration or allocated from heap using malloc at runtime.I wrote this program in C :
#include<stdio.h>
int main() {
int n, i;
scanf("%d", &n);
int a[n];
for (i=0; i<n; i++) {
scanf("%d", &a[i]);
}
for (i=0; i<n; i++) {
printf("%d ", a[i]);
}
return 0;
}
This code works fine.
My question is how this code can work correctly.Isn't it the violation of basic concept of C that array size must be declared before runtime or allocate it using malloc() at runtime.I'm not doing any of these two things,then why it it working properly ?
Solution to my question is variable length arrays which are supported in C99 but if I play aroundmy code and put the statement int a[n]; above scanf("%d,&n); then it's stops working Why is it so.if variable length arrays are supported in C ?
The C99 standard supports variable length arrays. The length of these arrays is determined at runtime.
Since C99 you can declare variable length arrays at block scope.
Example:
void foo(int n)
{
int array[n];
// Initialize the array
for (int i = 0; i < n; i++) {
array[i] = 42;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With