谁能解释一下什么是可变修改类型?
If we have an array
a[n]
andn
is not known at compile time thena
is a VLA. Given an arrayb[c][d]
wherec
andd
are not known until runtime impliesb
is a VLA, right?
在我的书中,他们说过可变修改类型包含 VLA。 而已;仅此而已。
如何创建指向可变修改类型的指针?
最佳答案
可变修改类型是 VLA(可变长度数组)。具有灵活数组成员的结构中有类似的类型,但我不打算进一步讨论灵活数组成员。
关于 VLA 的关键点是数组的维度直到运行时才知道。经典地,在 C89 和标准之前,数组的所有维度除了第一个维度必须是编译时已知的常量值(并且第一个维度可以指定为 int a[]
或 int b[][SIZE]
或 int c[][SIZE1][SIZE2]
,其中大小是常数)。
void some_function(int n)
{
int a[n];
int c = n+1;
int d = n+2;
int b[c][d];
another_function(n, a, c, d, b);
...
}
void another_function(int n, int a[n], int c, int d, int b[c][d])
{
...
}
a
和 b
都是可变长度数组。在 C99 之前,您不可能像那样编写 some_function()
;数组的大小必须在编译时作为编译时常量已知。同样,another_function()
的表示法在 C99 之前是不合法的。
你可以并且仍然可以(出于向后兼容性的原因,如果没有别的原因)编写 another_function()
的适度模拟:
enum { FIXED_SIZE = 32 };
void yet_another_function(int a[], int n, int b[][FIXED_SIZE], int c)
{
...
}
这不是一个完美的模拟,因为 FIXED_SIZE 是一个固定大小,但纯 C99 VLA 代码在那里有一个可变维度。因此,旧代码通常会使用对于最坏情况来说足够大的 FIXED_SIZE。
在 another_function()
中,名称 a
和 b
基本上是指向可变修改类型的指针。
否则,您的操作与固定大小的数组相同:
int z[FIXED_SIZE];
int (*z_pointer)[FIXED_SIZE] = &z;
int v[n];
int (*v_pointer)[n] = &v;
关于c - C语言中的可变修饰类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23529069/