Array of types in struct in c

I have such a structure

struct packet
{
int seqnum;
char type[1];
float time1;
float pri;
float time2;
unsigned char data[512];
}

I get the package in an array

char buf[529];

I want to take seqnum, the data is all separately. The following work with the type is performed. It gives meaning to me.

struct packet *pkt;
pkt=(struct packet *)buf;
printf(" %d",pkt->seqnum)
+5
source share
3 answers

No, this probably won't work and is usually a bad and broken way to do it.

You should use compiler-specific extensions to make sure that there is no invisible add-on between your structure members for something like this to work. For example, with gcc you do this with syntax __attribute__().

This is, therefore, not a figurative idea.

. , , , .

+7

, . , memcopy:

packet p;

memcpy(&p.seqnum, buf + 0, 4);

memcpy(&p.type[0], buf + 4, 1);

memcpy(&p.time1, buf + 5, 4);

.

, .

+4

, , ( , ..), . , , .

, , - (?), , ( ).

, , , . , C. gcc :

struct my_struct {
    int blah;
    /* Blah ... */
} __attribute__((packed));

, , ..

, __attribute__((packed)) !

Another solution, which is much more appropriate, is self-parsing. You simply select the appropriate structure and fill in its fields, looking for good information from your buffer. The sequence of instructions memcpyis likely to do the trick here (see Kerrek's answer)

+1
source

All Articles