简体   繁体   中英

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.

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:

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.

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. )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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