views:

192

answers:

5

I know its possible to increase the size of a dynamically allocated array.

But can I increase the size of a statically allocated array? If yes,how?

EDIT: Though this question is intended for C language, consider other languages too.Is it possible in any other language?

+1  A: 

in VB .NET it would be:

Redim Preserve ArrayName(NewSize)

not sure what langauge you're after though...

And I wouldn't use this command a lot... its terribly inefficient. Linked lists and growing data structures are much more efficient.

Jrud
I also agree with Keith Randall, even though it looks as though the statement I wrote redefines the size of the array the REASON it is inefficient is because behind the scenes it is really just making a second static array of the new size, copying the values into it, and then deleting the old one.
Jrud
A: 

No. It is not. There are two options here:

  1. Use a dynamic one
  2. Or,at the risk of wasting memory, if you have an idea about the maximum number of elements that the array will store, statically allocate accordingly

Yes, that was C.

Amit
+5  A: 

Simple answer is no, this cannot be done. Hence the name "static".

Now, lots of languages have things that look like statically allocated arrays but are actually statically allocated references to a dynamically allocated array. Those you could resize.

Keith Randall
A: 

If you're careful, you can use alloca(). The array is allocated on the stack, but in terms of the code style it's a lot like if you used malloc (you don't have to free it though, that's done automatically). I'll let you decide whether to call that a "static" array.

Ken Bloom
Isn't it a dynamic array you are talking about?
Ravi
I wasn't sure entirely what you felt was useful about static arrays. If the useful part is the fact that you don't have worry about freeing them (and you couldn't care less about whether the language provides nice pretty syntax to create them), then alloca will do the trick.
Ken Bloom
@Ravi: no, not "dynamic" as in "dynamic lifetime", because arrays allocated by alloca() have automatic lifetime (i.e. same as local variables). However, their size is determined at runtime.
newacct
A: 

No. Static allocation gives the compiler permission to make all kinds of assumptions which are then baked into the program during compilation.

Among those assumptions are that:

  1. it is safe to put other data immediately after the array (not leaving you room to grow), and
  2. that the array starts at a certain address, which then becomes part of the machine code of the program; you can't allocate a new array somewhere (and use it) because the references to the address can't be updated.

(Well, references could be updated, if the program was stored in ram, but self-modifying programs are highly frowned upon, and surely more trouble than dynamic arrays.)

Justin Love