简体   繁体   English

如何在结构(或等效结构)中定义指向可变长度数组 (VLA) 的指针?

[英]How can I define a pointer to variable length array (VLA) in a struct (or equivalent)?

I declared many pointers to variable length array (VLA) in a function to allocate 2-D arrays dynamically;我在 function 中声明了许多指向可变长度数组 (VLA) 的指针,以动态分配二维 arrays; for example,例如,

int M, N; // have some value
double (*arr1)[N] = calloc(M, sizeof(double [N]));
double (*arr2)[N] = calloc(M, sizeof(double [N]));
double (*arr3)[N] = calloc(M, sizeof(double [N]));
... // so many declarations

Because the function became very long, I tried to split it into several functions, each of which requires all that pointers as the argument.因为 function 变得很长,我试图将它拆分成几个函数,每个函数都需要所有的指针作为参数。 Instead of passing many things in the function (which is bad for a performance), I declared a struct containing all pointers globally to reduce the number of argument:我没有在 function 中传递很多东西(这对性能不利),而是声明了一个包含全局所有指针的结构以减少参数的数量:

struct ptrpack {
    int M, N;
    double (*arr1)[N];
    double (*arr2)[N];
    ...
};

// then each function just takes a single struct rather than many pointers
void foo(struct ptrpack p) {
    ...
}

However, a pointer to VLA is not allowed in struct.但是,结构中不允许指向 VLA 的指针。 GCC extension allows it if the struct definition is in a function, but the definition is in global scope in my case.如果结构定义在 function 中,则 GCC 扩展允许它,但在我的例子中,定义在全局 scope 中。

What is the best solution for this problem?这个问题的最佳解决方案是什么? I strongly prefer to use a pointer to VLA, not an ordinary pointer.我非常喜欢使用指向 VLA 的指针,而不是普通指针。

Declare the structure members to be pointers to arrays of unknown size (no size expression is supplied in the brackets):将结构成员声明为指向未知大小的 arrays 的指针(括号中未提供大小表达式):

double (*arr1)[];

Such pointers are compatible with pointers to variable length arrays because pointers to compatible types are compatible (C 2018 6.7.6.1 2), and an array of unknown size is compatible with any array with a compatible element type, per 6.7.6.2:此类指针与指向可变长度 arrays 的指针兼容,因为指向兼容类型的指针是兼容的 (C 2018 6.7.6.1 2),并且根据 6.7.6.2,未知大小的数组与具有兼容元素类型的任何数组兼容:

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value…对于要兼容的两个数组类型,两者都应具有兼容的元素类型,并且如果两个大小说明符都存在,并且是 integer 常量表达式,则两个大小说明符应具有相同的常量值......

Because the pointer type does not indicate the array size, you will not be able to use these members directly to access multiple dimensions.因为指针类型不指示数组大小,所以您将无法直接使用这些成员来访问多个维度。 For example, if p is the structure, p.arr1[i][j] will yield a compiler error.例如,如果p是结构, p.arr1[i][j]将产生编译器错误。 One way to use them is to assign them to temporary variables that include the type information:使用它们的一种方法是将它们分配给包含类型信息的临时变量:

double (*arr1)[p.N] = p.arr1;
… // arr1[i][j] works here.

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

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