[bitlug] Re: a useful c trick

  • From: Peeyush Prasad <peeyush@xxxxxxxxxx>
  • To: "Bitlug (E-mail)" <bitlug@xxxxxxxxxxxxx>
  • Date: Wed, 30 Jun 2004 17:02:32 +0530 (IST)

Hi Tc,
 Can you put line breaks every 80 cols?? I find things tough in pine
otherwise.I think this setting is available in almost all clients...
 see embedded.
On Wed, 30 Jun 2004, Turuvanur Pavan-A20404 wrote:

> Hi all,
> This is a kinda standard way to do it, but dunno how many of us here are 
> aware of it.
> There is a way of creating runtime variable length arrays, if you can call it.
> take a look at this structure :
> struct net_packet
> {
>   int hdr_ele1;
>   int hdr_ele2;
>   char hdr_ele3;
>   int hdr_ele4;
>   char payload[1];
> };
> Note that the array is the last member of the structure and is of size 1, but 
> its usage is different.
> During the development of code, lets say that this structure is used to send 
> payloads of different sizes. In that case, all we need to do is to declare a 
> struct net_packet pointer, malloc memory of size (payload + hdr_elements). 
> The payload can be referred to, using the array payload.
> For example, if the payload is 1500 bytes in size, then,
> struct net_packet *pkt = (struct net_packet*)malloc(1500+3*sizeof(int)+1);
> The payload can simply be addressed as pkt->payload[x].Any variation in the 
> size of the payload can be taken care of in malloc.
> The other way to do it would be to have a pointer in the structure, malloc 
> separately for it and maintain the pointer. The above method gets rid of this 
> inconvienience and also provides the advantages of the array mechanism.
It looks like a cute way of accessing regions of memory... However, I
think keeping a pointer and malloc()ing only the payload is an equally
good method.The array access mechanism is available here as well, and
you also would have to undergo the 'inconvenience' of maintaining your
pointer.I would prefer payload malloc, as at least I am explicitly aware
of a fixed header and variable payload.
 Also, if the header changes, I just add another field to my
structure,while you have to look for and modify every malloc you make...
  but nice trick, nonetheless... and good to see activity!!

-- P
> Another typical usage of this would be in passing messages where one might 
> have a message type, message length, and then the message itself (of variable 
> length).
> TC

Other related posts: