lordhog
lordhog

Reputation: 3707

Initialize an array at specific offset using a structure, possible?

Say I have a structure like the following

typedef struct {
   char field1: 4,
   char field2: 4
} MyStruct_t;

Now, there is a large buffer of data that is declared

char BigBuffer[2048]

I want to initialize parts of the array using the structure defined above, how would I do that?

char BigBuffer[2048] = {
   [10]  = (MyStruct_t)(.field1 = 5, field2 = 7),
   [20]  = (MyStruct_t)(.field1 = 7, field2 = 4),
   [200] = (MyStruct_t)(.field1 = 1, field2 = 9) }

Is this possible or something similar?

I already have a different solution using #define with masking and shifting,

char BigBuffer[2048] = {
   [10]  = (5 & 0xf) << 4 | (7 & 0xf),
   [20]  = (7 & 0xf) << 4 | (4 & 0xf),
   [200] = (1 & 0xf) << 4 | (9 & 0xf) }

As a note, I am aware the packing of the bit fields in the structure is left up to the compiler unless a directive is used to specify. Just trying to demonstrate the intent. Thanks!

Upvotes: 1

Views: 510

Answers (1)

Stan
Stan

Reputation: 787

Not sure if I got your question correctly, but I still believe (5 & 0xf) << 4 | (7 & 0xf) is more elegant.

#include <stdio.h>

typedef struct{
    char field1:4;
    char field2:4;
}MyStruct_t;

int main(){
    char b[2] = {
        [0] = *(char*)&(MyStruct_t){.field1 = 5, .field2 = 7},
        [1] = *(char*)&(MyStruct_t){.field1 = 7, .field2 = 4}
    };

    printf("%02x %02x\n", b[0], b[1]);
    return 0;
}

Upvotes: 1

Related Questions