声明中的数组长度可以是非恒定的吗? [英] Can array length in declaration be non-constant?

查看:54
本文介绍了声明中的数组长度可以是非恒定的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C语言中的数组声明有些困惑.我知道可以这样做:

I am a bit confused about array declaration in C. I know that it's possible to do this:

int a[20];  // Reserved space for 20 int array
int b[] = {32, 431, 10, 42};  // Length in square brackets is auto-calculated
int *c = calloc(15, sizeof(int));  // Created a pointer to the dynamic int array

但是有可能这样做吗?:

But is it possible to do this?:

int my_array[sizeof(int) * 5];

它是有效的代码,还是数组长度应该是一个常量表达式(在ANSI C中)?

Is it a valid code, or an array length should be a constant expression (in ANSI C)?

推荐答案

sizeof(int)* 5 在您的问题的示例语句中使用: int my_array [sizeof(int)*5]; ,是一个常量表达式,因此尽管它不能很好地说明您的主要问题,但它是C数组声明的合法语法.

sizeof(int) * 5 used in the example statement in your question: int my_array[sizeof(int) * 5];, is a constant expression, so although it does not serve as a good illustration of your primary question, it is legal syntax for C array declaration.

除了 C99 可变长度数组在最新的C编译器实现中是可选的.(在 C99 中,必须包含VLA.)

With the exception of C99, variable length arrays are optional in most recent C compiler implementations. (In C99 inclusion of VLA is mandated.)

因此,如果您的编译器支持VLA,则下面是示例:

So, if your compiler supports VLA, the following are an examples:

char string[100] = {0};
scanf("%99s", string);
int VLAarray1[strlen(string)+1];//per question in comments about functions to size array.
memset(VLA1array, 0, sizeof(VLAarray1));//see Note below for initialization

int arrayLen = 0;
scanf("%d", &arrayLen);
int VLAarray2[arrayLen];
memset(VLAarray2, 0, sizeof(VLAarray2));//see Note below for initialization
int nonVLAarray[100] = {0};//initialization during declaration of nonVLA

注意 :VLA在声明期间无法以任何形式初始化.与所有变量一样,最好在后续语句中通过将值显式分配给其整个内存区域来对其进行初始化.

Note: that VLAs cannot be initialized in any form during its declaration. As with all variables though it is a good idea that it be initialized in subsequent statements by explicitly assigning values to its entire region of memory.

将VLA作为函数参数传递不包含在您的问题范围内,但是如果有兴趣,可以进行很好的讨论关于这个话题.

Passing VLAs as function arguments is not included within the scope of your question, but should it be of interest, there is a good discussion on that topic here.

这篇关于声明中的数组长度可以是非恒定的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆