结构中可变长度的数组 [英] Array of variable length in struct

查看:86
本文介绍了结构中可变长度的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了2种结构来表示C语言中的图像(一个像素和一个图像).

I've created 2 structures to represent images (a pixel and an image one) in C.

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

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

我收到一个错误消息,说图像的定义中未定义宽度和高度.我不知道为什么会收到该错误以及如何解决该错误

I am getting an error saying that width and heigth are not defined in the definition of image. I don't get why I'm getting that error and how I can solve it

推荐答案

我会建议这样的替代方案:

i would suggest an alternative like this:

typedef struct 
{
int width;
int heigth;
struct pixel *pixels;
} image;

每次,您都需要分配:

image img;
/* init */
img.pixels=malloc(sizeof(struct pixel)*img.width*img.height);

*(img.pixels+img.height*i+j)代表img.pixels[i][j].

这篇关于结构中可变长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆