繁体   English   中英

声明C数组

[英]Declaring C arrays

int array[5][3];

(显然)创建了一个5 x 3的多维C数组。但是,

int x = 5;
int array[x][3];

没有 我一直以为会。 我对C数组不了解? 如果它们仅允许常量定义C数组的长度,是否有某种方法可以解决此问题?

在ANSI C(aka C89)中,所有数组维都必须是编译时整数常量(这不包括声明为const变量)。 一个例外是,在某些情况下,例如函数参数, 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添加了一个称为可变长度数组 (VLA)的新功能,其中第一维允许为非恒定大小,但仅适用于在堆栈上声明的数组(即具有自动存储功能的数组)。 全局阵列(即具有静态存储的阵列)不能是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 ++ 具有VLAS,尽管许多C / C ++编译器,如克++支持VLAS在它们的C实现还支持VLAS在C ++中作为扩展。

 int x = 5;
 int array[x][3];

是的,它确实。 这是一个C99可变长度数组。 确保切换到C99模式,并确保在块或函数作用域声明了array 可变长度数组不能在文件范围内声明。

尝试:

const int x=5;
int array[x][3];

正如您所说的x必须是常数,否则想想如果在程序中间更改x的值会发生什么,那将是array的维数:(

但是通过声明它常量,如果您更改x的值,则会出现编译错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM