﻿ 具有灵活数组成员的结构数组如何表现？ - 代码日志

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

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

The sizeof operator on such a struct is required to give the offset of the flexible array member.

#define LENGTH 10

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

struct vector *v0 = calloc(1, sizeof(*v0) + LENGTH * sizeof(v0->array[0]));
v0->length = LENGTH;

size_t i;
for (i = 0; i < v0->length; i++) {
v0->array[i] = (double) i;
}

struct vector v1;
struct vector v2;

arr[0] = *v0;
arr[1] =  v1;
arr[2] =  v2;

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

#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;
}