views:

407

answers:

5

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?
+2  A: 

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)
swillden
If you drop the `(int*)` cast, the compiler will generate an error if you forget to include the file defining `malloc`. Thus it's best practice not to include the cast.
Mark Ransom
`int *a = malloc(s * sizeof *a)`
AndreyT
+11  A: 

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

JaredPar
Oh i see. thank you. so all elements of the array still located on stack?
tsubasa
Yes, they are. If that is bad, use malloc as suggested in other answers.
Keith Randall
A: 

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) );
Dirk Eddelbuettel
+1  A: 

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.

AndreyT
A: 

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.

Bootcamp
Allocating memory on the stack is simply a matter of adjusting the stack pointer - and there is *no* fundamental reason why the stack pointer can only be adjusted by values known at compile time. Indeed, the most recent C standard allows automatic variables whose sizes are determined at runtime, and there is also a common extension `alloca()` which provided the same thing for years before *that*.
caf