int array[5][3];
(显然)创建一个 5 x 3 的多维 C 数组。但是,
int x = 5;
int array[x][3];
不会不会。我一直认为会的。我对 C 数组有什么不了解?如果他们只允许一个常量来定义 C 数组的长度,是否有办法以某种方式解决这个问题?
最佳答案
在 ANSI C(又名 C89)中,所有数组维度必须是编译时整数常量(这不包括声明为 const
的变量)。一个异常(exception)是第一个数组维度在某些上下文中可以写成一组空括号,例如函数参数、extern
声明和初始化。例如:
// The first parameter is a pointer to an array of char with 5 columns and an
// unknown number of rows. It's equivalent to 'char (*array_param)[5]', i.e.
// "pointer to array 5 of char" (this only applies to function parameters).
void some_function(char array_param[][5])
{
array_param[2][3] = 'c'; // Accesses the (2*5 + 3)rd element
}
// Declare a global 2D array with 5 columns and an unknown number of rows
extern char global_array[][5];
// Declare a 3x2 array. The first dimension is determined by the number of
// initializer elements
int my_array[][2] = {{1, 2}, {3, 4}, {5, 6}};
C99 添加了一个名为可变长度数组 (VLAs) 的新特性,其中第一个维度允许是非常量,但仅适用于在堆栈上声明的数组(即那些带有 < em>自动存储)。全局数组(即具有静态存储 的数组)不能是 VLA。例如:
void some_function(int x)
{
// Declare VLA on the stack with x rows and 5 columns. If the allocation
// fails because there's not enough stack space, the behavior is undefined.
// You'll probably crash with a segmentation fault/access violation, but
// when and where could be unpredictable.
int my_vla[x][5];
}
请注意,最新版本的 C 标准 C11 使 VLA 成为可选的。 Objective-C 基于 C99 并支持 VLA。 C++ 没有有 VLA,尽管许多 C/C++ 编译器(例如在其 C 实现中支持 VLA 的 g++)也支持 C++ 中的 VLA 作为扩展。
关于c - 声明 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802890/