As I know, an array needs to have a specific size before compiling time in c.
I wonder why this code still works?
int s;
printf("enter the array size: ");
scanf("%d",&s);
int a[s]; // Isn't s value determined at run time?
As I know, an array needs to have a specific size before compiling time in c.
I wonder why this code still works?
int s;
printf("enter the array size: ");
scanf("%d",&s);
int a[s]; // Isn't s value determined at run time?
If you need to allocate an array with dynamic size, you have to get it from the heap, with malloc().
int *a = (int*)malloc(sizeof(int) * s)
Array sizes need to be known with ANSI 89 C. The 99 version of the spec removed this limitation and allowed for variable sized arrays.
Here is the documentation no the GNU version of this feature
You are confusing two things here.
1) Determining the size of an already allocated array (which your title implies): divide sizeof()
for the total by the size of one (say, the first) element:
sizeof(a)/sizeof(a[0])
2) Dynamically allocating memory as your question asks:
int *a = (int*)malloc( s * sizeof(int) );
This code is supported by C99 language specification. This code is also supported by GCC compiler in C89/90 mode as an extension.
So, the answer to your question (why it "works") depends on how you are compiling it. In general case, this will not even compile by a C89/90 compiler.
Its important to understand how memory is allocated to variable by a compiler to give proper answer to your question. There are two modes in which memory is allocated to variable, it can be on a heap or it can be on a stack. Memory on a heap is allocated dynamically. So a variable that is allocated memory on a heap can be given its size during run time.
The arrays in case of C are given memory on a stack. For providing memory on a stack the size of the memory should be known to the compiler during compile time. So that during run time that much memory can be set aside for the variable on the stack. That is the reason you cannot decide the size of the array at run time as far as C language is concerned.