c - Copy a structure to a member of another structure -
i'm on sdcc 3.4 , midi project musical instrument, , it's couple of days i'm struggling this... find somehow difficult explain, here try make better example. basically, scanning button presses, send midi information , lit leds accordingly. need sort of database holding data related each button, of part must constant (ids of buttons , leds) , part can variable because can varied user. @ initialization phase need assign constant part structure , leave variable part unchanged. when user modifies function of button, need overwrite variable part , leave constant part unchanged.
// structure constant part typedef struct { unsigned char btnid; // holds n. of input pin button unsigned char ledid; // holds n. of output pin led } sbtnconst; // structure variable part typedef struct { unsigned char ccnum; // holds cc number send unsigned char ccval; // holds cc value tu send } sbtnvar; // structure containing data typedef struct { sbtnconst c; sbtnvar v; } sbutton; // declare array of button structures // these contain both constant , variable data sbutton button[4]; // initialize constant structure constant part const sbtnconst cbtndefinitions[4] = { { 15, 0 }, { 14, 1 }, { 10, 8 }, { 12, 5 }, };
now, need copy whole content of cbtndefinitions[]
button[]->c
. if
memcpy(&button->c, &cbtndefinitions, sizeof(cbtndefinitions));
the data copied in c , v sequentially, not in member c.
the rest of code in main loop() goes this:
void dobutton(sbutton *btn, unsigned char value) { litled(btn->c.ledid, !value); sendmidicc(btn->v.ccnum, btn->v.ccval); } // callback function called every time button has been pushed void abuttonhasbeenpushed(unsigned char id, unsigned char value) { unsigned char i; (i=0; i<num_of_buttons; ++i) if (i == button[i].c.btnid) dobutton(&button[i], value); }
of course may have different types of buttons, can use sbutton structure other purposes, , have them processed same functions.
you need loop, source cbtndefinitions
contiguous memory area whilst destination consists of 4 separate memory areas.
you can memcpy
:
int i; (i = 0; < 4; ++i) { memcpy(&button[i].c, cbtndefinitions + i, sizeof(sbtnconst)); }
but simple assignment works gcc:
int i; (i = 0; < 4; ++i) { button[i].c = cbtndefinitions[i]; }
Comments
Post a Comment