且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有灵活数组成员的结构的数组如何表现?

更新时间:2023-11-24 23:07:58

以灵活数组作为最后一个成员的结构不能用作其他结构的成员或数组元素.在这种结构中,由于其大小为0个元素,因此无法使用柔性数组.乔纳森·莱弗勒(Jonathan Leffler)引用的C标准是明确的,尽管所使用的语言技术性很强,并且通过搜索 flexible 不能在标准中找到这些段落.

Structures with a flexible array as their last member cannot be used as members of other structures or as array elements. In such constructions, the flexible array cannot be used as it has a size of 0 elements. The C Standard quoted by Jonathan Leffler is explicit, although the language used is quite technical and the paragraphs cannot be found in the Standard by searching for flexible.

编译器应为您的结构向量数组发出错误.

The compiler should have issued an error for your array of struct vector.

在您的程序中,您应该改为使用指向struct vectors的指针数组,每个指针都指向为其灵活数组中的适当数量的元素分配的对象.

In your program, you should instead use an array of pointers to struct vectors, each pointing to an object allocated for the appropriate number of elements in the its flexible array.

这是修改后的版本:

#include <stdio.h>
#include <stdlib.h>

struct vector {
    size_t length;
    double array[];
};

struct vector *make_vector(size_t n) {
    struct vector *v = malloc(sizeof(*v) + n * sizeof(v->array[0]));
    v->length = n;
    for (size_t i = 0; i < n; i++) {
        v->array[i] = (double)i;
    }
    return v;
}

int main(void) {
    struct vector *arr[3];

    arr[0] = make_vector(10);
    arr[1] = make_vector(5);
    arr[2] = make_vector(20);

    for (size_t n = 0; n < 3; n++) {
        for (size_t i = 0; i < arr[n]->length; i++) {
            printf("arr[%zu]->array[%2zu] equals %2.0lf.\n",
                   n, i, arr[0]->array[i]);
        }
    }
    return 0;
}