Can I increase the size of a statically allocated

2019-08-01 07:55发布

问题:

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:

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.



回答2:

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.



回答3:

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.



回答4:

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.



回答5:

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.)