Home > Mobile >  Assigning empty array to a pointer at compile time in C
Assigning empty array to a pointer at compile time in C

Time:10-22

I have a structure in C which is intended to store information about character lcd's. It looks like this:

typedef struct CharLCD {
    uint8_t rows, columns, currentLine;
    uint8_t* lineAddress;
    uint8_t* pContent;
} CharLCD;

I would like to create an instance of that structure and populate pContent with pointer to empty array of known size. I solved this problem for the lineAddress by listing all the values but I expect the pContent to store 64 values which makes that approach unpractical. I can assign the values programmatically later but I need to create the array:

CharLCD lcd16x4 ={
    .rows = 4,
    .columns = 16,
    .currentLine = 0,
    .lineAddress = {0x00, 0x40, 0x10, 0x50},
    .pContent = /*uninitialized array of size 64*/
};

Is there a more elegant way to achieve this than creating an empty array as a new variable and then storing the pointer to pContent? The code is intended to run on an embedded platform which doesn't allow dynamic allocation of memory.

Thank you for any help.

CodePudding user response:

You can use a compound literal.

CharLCD lcd16x4 ={
    .rows = 4,
    .columns = 16,
    .currentLine = 0,
    .lineAddress = {0x00, 0x40, 0x10, 0x50},
    .pContent = (uint8_t[64]){0}
};

You could also just declare the 64-element array and refer to that in the initialization of the structure.

uint8_t lcd16_content[64];
CharLCD lcd16x4 ={
    .rows = 4,
    .columns = 16,
    .currentLine = 0,
    .lineAddress = {0x00, 0x40, 0x10, 0x50},
    .pContent = lcd16_content
};

The only effective difference between these is that the array has a name independent of the structure member.

  • Related