简体   繁体   English

初始化结构中的2D数组的指针

[英]Initialize pointer to 2D array in structure

What I try to get, is a structure, which contains an 2D array of bytes which should store a binary picture. 我试图得到的是一个结构,其中包含一个2D字节数组,应该存储一个二进制图片。

typedef enum{
    PIC_ID_DOUBLE_UP,
    PIC_ID_DOUBLE_DOWN,
}PICPictureId_t;

typedef struct{
    PICPictureId_t  picId;
    uint8           width;
    uint8           height;
    uint8           (**dataPointer);
}PICPicture_t;

The dimensions (in pixels) are determined by the width and height. 尺寸(以像素为单位)由宽度和高度确定。 Now I tried to initialize an array of pictures. 现在,我尝试初始化图片数组。 I want to store the whole data in the flash. 我想将所有数据存储在闪存中。

PICPicture_t pictures[] = {
    {
        .height       = 3,
        .width        = 16,
        .picId        = PIC_ID_DOUBLE_UP,
        .dataPointer  = ???        
    }
};

How could I initialize the pointer to the data? 如何初始化指向数据的指针? I get a version which compiles (after studying the answer here: A pointer to 2d array ), if I use a pointer to an array in the picture struct and then set the pointer to the first element of the doubleUp 2D array: 如果我在图片结构中使用指向数组的指针,然后将指针设置为doubleUp 2D数组的第一个元素,则可以获得编译的版本(在此处研究答案: 指向2d array的指针之后):

typedef struct{
    PICPictureId_t  picId;
    uint8           width;
    uint8           height;
    uint8           (*dataPointer)[2];
}PICPicture_t;

uint8 doubleUp[3][2] = {
    {0x12 ,0x13},
    {0x22 ,0x32},
    {0x22 ,0x32}
};


PICPicture_t pictures[] = {
    {
        .height       = 3,
        .width        = 16,
        .picId        = PIC_ID_DOUBLE_UP,
        .dataPointer  = &(doubleUp[0]),
    }
};

But here I have to declare the dimension of the second array but I want to make the structure idependent of the dimension and use for this the height and width field. 但是在这里,我必须声明第二个数组的维,但是我想使结构独立于维,并为此使用height和width字段。

Use a pointer to a one-dimensional array and index it manually: 使用指向一维数组的指针并对其手动进行索引:

typedef struct{
PICPictureId_t  picId;
uint8           width;
uint8           height;
uint8           *dataPointer;
}PICPicture_t;

The image data will have to change to a single dimension: 图像数据将必须更改为一个维度:

uint8 d[6] = {
    0x12 ,0x13,
    0x22 ,0x32,
    0x22 ,0x32
};

You can initialize it: 您可以初始化它:

PICPicture_t s = { 3 , 2, ID , d }; 

And interpret it as a 2d array: 并将其解释为二维数组:

uint8 x = 1;
uint8 y = 2;
uint8 value = s.dataPointer[y*width+x];  

(I changed the width to 2 from 16 so the example is clearer. The idea is the same if you plan to access single bits. ) (我将宽度从16更改为2,因此示例更加清晰。如果您打算访问单个位,则想法是相同的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM