[bitlug] a useful c trick

  • From: Turuvanur Pavan-A20404 <pavan.tc@xxxxxxxxxxxx>
  • To: "Bitlug (E-mail)" <bitlug@xxxxxxxxxxxxx>
  • Date: Wed, 30 Jun 2004 09:45:03 +0530

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.

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: