在c中虽然支持了变长数组,但是在使用的时候还是会有诸多限制。比如分配在栈上,也就是说不能返回变长数组的指针,同时还增加了栈溢出的风险,以下是几种不能使用的场景。
- 不能使用extern声明的长度
- 在struct members中定义长度
- 在static变量中定义长度
- 在函数定义中定义长度
extern int n;
int A[n]; // invalid: file scope VLA
extern int (*p2)[n]; // invalid: file scope VM
int B[100]; // valid: file scope but not VM
void fvla(int m, int C[m][m]); // valid: VLA with prototype scope
void fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA
{
typedef int VLA[m][m]; // valid: block scope typedef VLA
struct tag {
int (*y)[n]; // invalid: y not ordinary identifier
int z[n]; // invalid: z not ordinary identifier
};
int D[m]; // valid: auto VLA
static int E[m]; // invalid: static block scope VLA
extern int F[m]; // invali