gpt4 book ai didi

c - 通用字符缓冲区用作具有灵活数组成员的结构数组

转载 作者:行者123 更新时间:2023-11-30 16:56:25 24 4
gpt4 key购买 nike

You can't have arrays of structures with flexible array members.

这是 this question 的 TL;DR 。仔细想想,这很有道理。

但是,可以模拟具有灵活数组成员的结构数组 - 让我们称之为swfam - 固定大小,如下所示:

#include <assert.h>
#include <stdlib.h>


typedef struct {
int foo;
float bar[];
} swfam_t; // struct with FAM

typedef struct { // this one also has a FAM but we could have used a char array instead
size_t size, // element count in substruct
count; // element count in this struct
char data[];
} swfam_array_t;


#define sizeof_swfam(size) (sizeof(swfam_t) + (size_t)(size) * sizeof(float))


swfam_array_t *swfam_array_alloc(size_t size, size_t count) {
swfam_array_t *a = malloc(sizeof(swfam_array_t) + count * sizeof_swfam(size));

if (a) {
a->size = size;
a->count = count;
}

return a;
}

size_t swfam_array_index(swfam_array_t *a, size_t index) {
assert(index < a->count && "index out of bounds");
return index * sizeof_swfam(a->size);
}

swfam_t *swfam_array_at(swfam_array_t *a, size_t index) {
return (swfam_t *)&a->data[swfam_array_index(a, index)];
}


int main(int argc, char *argv[]) {
swfam_array_t *a = swfam_array_alloc(100, 1000);
assert(a && "allocation failed");

swfam_t *s = swfam_array_at(a, 42);

s->foo = -18; // do random stuff..
for (int i = 0; i < 1000; ++i)
s->bar[i] = (i * 3.141592f) / s->foo;

free(a);
return 0;
}

该技巧在 C99/C11 中有效吗?我是否潜伏在未定义的行为中?

最佳答案

实现此目的的一种方法是使用指针成员而不是灵活数组。然后,您必须通过 malloc() 等手动分配其大小。等人。 [] 通常仅在数组在声明时初始化时使用,这对于 struct 是不可能的,它本质上是一个定义,而不是声明。立即声明结构类型实例的能力不会改变定义的性质,这只是为了方便。

typedef struct {
int foo;
float* bar; } swfam_t; // struct with FAM

关于c - 通用字符缓冲区用作具有灵活数组成员的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39924068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com