0

I am trying to assign values in main program.

typedef struct PointStructure 
{   unsigned char x;    
    unsigned char y; 
    unsigned char offset; 
    unsigned char page;
}point;

volatile far point p;
volatile far point AryP[5];

The only way I could assign values to the structure p in main program is

p.x=10;
p.y=20;
p.offset=0;
p.page=1;

This way it will take a lot of space and time for me to assign values to the arrays. Is there a better way to do this?

Following ways did not work for me..

p = {10, 20, 0, 1};

p = {.x = 10, .y=20, .offset=0, .page=1};
Dolphin
  • 1
  • 1
  • `={10, 20, 0, 1}` should work at the initialisation stage. For assign, it isn't defined. `.fieldname=value` is GNU C only, no surprise it isn't recognised. – keltar Jun 18 '14 at 16:43
  • Thanks fo your response. Yes it works at the initialization stage. But based on certain flags, I have to assign the values at runtime. I was hoping to find an easier way to assign in the main program. Is there any other way to assign values than p.x=10; and so on? – Dolphin Jun 18 '14 at 18:21
  • `point t = { 10, 20, 0, 1}; memcpy(&p, &t, sizeof(t));`. C99 adds compound literals for this, but I guess it isn't available on your compiler. – keltar Jun 18 '14 at 18:26
  • I have to do this for many arrays (only when certain flags change) and may not be the most efficient way. I was hoping for something straight forward like we assign at initialization stage. Thanks though. – Dolphin Jun 18 '14 at 18:56
  • Well, memcpy is very efficient as compiler knows what it does and may inline it heavily; but I wouldn't count on it on old compiler. But still, either that or define a macro that will expand to assigning individual fields - I see no other way for C89. – keltar Jun 18 '14 at 18:59
  • Thanks for confirming that there is no direct way of doing this - I thought I was missing something. – Dolphin Jun 18 '14 at 19:04

1 Answers1

0
p = {10, 20, 0, 1};

p = {.x = 10, .y=20, .offset=0, .page=1};

The above method is incorrect, unless you use it as initialization:

volatile far point p = {.x = 10, .y=20, .offset=0, .page=1};

To assign value into a structure, the following is the only way:

p.x=10;
p.y=20;
p.offset=0;
p.page=1;

There is no any way to assign multiple members in the same time, unless you make a function to do it.

void assignValue(point *p, x, y, offset, page)
{
      p->x = x;
      p->y = y;
      p->offset = offset;
      p->page = page;
}

Therefore you can just assign the value like this:

assignValue(&p, 10, 20, 0, 1);
Jing Wen
  • 20
  • 4