gpt4 book ai didi

c - 结构体中的可变长度数组

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

我在 C 中创建了 2 个结构来表示图像(一个像素和一个图像)。

typedef struct pixel {
unsigned char red;
unsigned char green;
unsigned char blue;
};

typedef struct image {
int width;
int height;
struct pixel pixels[width][height];
};

我收到一条错误消息,指出图像结构的定义中未定义宽度和高度。我不明白为什么会出现该错误或如何解决它?

最佳答案

在 C99 及更高版本中,您可以在结构末尾有一个(一维)灵活数组成员 (FAM):

§6.7.2.1 Structure and union specifiers

¶18 As a special case, the last element of a structure with more than one named member mayhave an incomplete array type; this is called a flexible array member. In most situations,the flexible array member is ignored. In particular, the size of the structure is as if theflexible array member were omitted except that it may have more trailing padding thanthe omission would imply. However, when a . (or ->) operator has a left operand that is(a pointer to) a structure with a flexible array member and the right operand names thatmember, it behaves as if that member were replaced with the longest array (with the sameelement type) that would not make the structure larger than the object being accessed; theoffset of the array shall remain that of the flexible array member, even if this would differfrom that of the replacement array. If this array would have no elements, it behaves as ifit had one element but the behavior is undefined if any attempt is made to access thatelement or to generate a pointer one past it.

这意味着你可以写:

typedef struct image
{
int width;
int height;
struct pixel pixels[];
} image;

但是您必须自己进行 2D 到 1D 索引映射。您还必须小心如何分配结构(必要时,它将由 malloc() 分配,否则数组的大小将为零)。

请注意为 typedef 添加的名称(我选择 image 来匹配结构标记,但您可以选择您喜欢的任何其他名称)。没有名称的 typedef 是“有效”但没有用 - 您可以省略 typedef 并获得相同的结果。

您可能会使用:

image *ip = malloc(sizeof(image) + width * height * sizeof(struct pixel));

if (ip != 0)
{
ip->width = width;
ip->height = height;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
ip->pixels[i*width + j] = default_pixel_value;
}
…use ip…
free(ip);
}

我不确定是否有一个好的方法来获取 2D 数组作为 FAM。

关于c - 结构体中的可变长度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153932/

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