0

I have these structures containing some GPS data:

typedef struct Traw_dat {
  int32_t iTOW;
  int16_t week;
  double cpMes;
  double prMes;
  double doMes;
  int8_t mesQI;
  int8_t cno;
  uint8_t lli;
}raw_dat;

typedef struct Tmsg_dat{
    char syncw[8];
    uint32_t msg_id;
    raw_dat raw[32];
//        struct eph_dat eph[32];
    char nmea[2][128];
}msg_dat;

I have to sent the msg_dat structure from my program in C through a pipe to some program in octave, which will do some calculations with it.

I thought that simple

msg_dat tab;
....
int check = write(pipe_fd,tab,sizeof(msg_dat));

could do the trick, but my collegue told me, that structures in C don't guarantee cuntinuity and order of its items. Is that true?

if yes, is this awfull thing a correct way, how to do it?

//output_fd - pipe, should check if writes are correct
write(output_fd,tab->syncw,8);
write(output_fd,&(tab->msg_id++),4);
for (int i = 0; i < 32 ; i++ ){
    write(output_fd,&(tab->raw[i].iTOW),4);
    write(output_fd,&(tab->raw[i].week),2);
    write(output_fd,&(tab->raw[i].cpMes),8);
    write(output_fd,&(tab->raw[i].proMes),8);
    write(output_fd,&(tab->raw[i].doMes),8);
    write(output_fd,&(tab->raw[i].mewQI),1);
    write(output_fd,&(tab->raw[i].cno),1);
    write(output_fd,&(tab->raw[i].lli),1);
}
//    for(int i = 0; i < 32 ; i++){
//        write(ephdat->......
//    }
write(output_fd,&(tab->nmea[0],128);
write(output_fd,&(tab->nmea[1],128);

EDIT: This question is only from half a duplicate of the original one, there is also the second part, which is not answered there...

Charlestone
  • 1,248
  • 1
  • 13
  • 27
  • 3
    Order is guaranteed, but padding/packing may vary. – Carl Norum Apr 01 '16 at 17:00
  • 1
    [Online C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), 6.7.2.1/15: "Within a structure object, the non-bit-field members and the units in which bit-fields reside have **addresses that increase in the order in which they are declared.**". Emphasis added. So yes, order is guaranteed. Continuity/adjacency is not guaranteed; there may be padding bytes between members, and their values will be indeterminate. – John Bode Apr 01 '16 at 17:18
  • 1) Please detail why the "second part" is of concern since the first part is answered yes, a structure does guarantee continuity. 2) The "awfull thing" has problems A) It may pack differently than `write(pipe_fd,tab,sizeof(msg_dat))` B) assumes sizes (`double`) – chux - Reinstate Monica Apr 01 '16 at 19:26
  • 1) because I have to read it on the other side of the pipe a if there would be some "undefined" padding between elements, it would be hard to load it back, so I have to send it element by element. 2. I asked if there is some better approach than what I have written. I'm aware of the problem with doubles and hopefully covered it. – Charlestone Apr 02 '16 at 14:31

0 Answers0