Can I increase the size of a statically allocated

2019-08-01 07:23发布

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?

5条回答
放我归山
2楼-- · 2019-08-01 08:07

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.

查看更多
放我归山
3楼-- · 2019-08-01 08:10

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.

查看更多
成全新的幸福
4楼-- · 2019-08-01 08:14

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

查看更多
戒情不戒烟
5楼-- · 2019-08-01 08:19

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.

查看更多
Evening l夕情丶
6楼-- · 2019-08-01 08:20

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.

查看更多
登录 后发表回答