Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

c - Why can't the size of a static array be made variable?

Related but not quite duplicate as it discusses C++:
can we give size of static array a variable

I am defining an array in one of the child files as follows.

static int arr[siz];

Here siz is a global variable available to the child file. But the gcc compiler produces the following error :

<filename>: <line_num> : error : storage size of ‘arr’ isn’t constant

Why can't I define a static array of variable size ?

EDIT : This seems to be a problem only for static int type. If I change the variable type of arr from static int to int, the error goes away, even though the size of array is still dependent on a variable siz.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since the size of the array you declare is not constant, what you have is an Variable Length Array(VLA). VLA are allowed by the c99 standard but there are some limitations associated with it. You cannot have an variable length array with static or extern storage class specifier.

You have an VLA with static storage specification and it is not allowed by the C99 Standard.

Reference:

c99 Standard: 6.7.5.2/8

EXAMPLE 4 All declarations of variably modi?ed (VM) types have to be at either block scope or function prototype scope. Array objects declared with the static or extern storage class speci?er cannot have a variable length array (VLA) type. However, an object declared with the static storage class speci?er can have a VM type (that is, a pointer to a VLA type). Finally, all identi?ers declared with a VM type have to be ordinary identi?ers and cannot, therefore, be members of structures or unions.

So if you want a dynamic size array with static storage specifier you will have to use a dynamic array allocated on heap.

#define MAX_SIZE 256
static int* gArr;
gArr = malloc(MAX_SIZE * sizeof(int));

EDIT:
To answer your updated question:
When you remove the static keyword from the declaration, the storage specifier of the declared array changes from static to global, note the standard quote above, it clearly mentions the restriction that VLAs are not allowed with static and extern storage specification. Clearly, you are allowed to have an VLA with global storage specification, which is what you have once you remove the static keyword.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...