Typecast struct pointer

Guys I have a small problem could anyone explain please what does the following line does please ?
1
2
3
4
5
char packet[65536];
   IPV4_HDR *v4hdr = NULL; //(IPV4_HDR is a structure)
   v4hdr = (IPV4_HDR *)packet; //<- what does this line do ?

Last edited on
It makes the pointer v4hdr point to the array packet, as if the array was an object of type IPV4_HDR.
Can you please explain a little bit more please ? What do I need this for ? Couldn't I just add the packet[65536] into the structure ?
Last edited on
Couldn't I just add the packet[65536] into the structure ?


No. The inside of a structure is defined once and once only. Here's an example:

1
2
3
4
5
struct breakfast
{
  int eggs;
  int bacon;
}


It's set. You cannot just add things into it mid-program. If you want to change the structure, you have to rewrite it.

What do I need this for ?

It looks like a simple way of setting aside 65536 bytes for use as a IPV4_HDR object. Seems an awfully roundabout way of doing it when you could just make an actual IPV4_HDR like this:

IPV4_HDR aNiceNewObject;
You have to cast the char* to an IPV4_HDR* in order for it to work syntactically.

I would say those lines are too far out of context to make sense. We can only assume that sizeof(IPV4_HDR) == 65536.

One way to try to put it into context:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MemAlloc
{
private:
  char* memory;
public:
  MemAlloc(unsigned int size) { memory = new char[size]; }
  ~memAlloc(void) { delete [] memory; }

  char* getMemory(unsigned int amount)
  {
    // Find a free block of "memory" the size of amount
    return thatBlock;
  }
  // A bunch of other functions for handling the "memory" array's blocks
};

int main(void)
{
  MemAlloc myMemoryAllocator(1000000);  // A 1,000,000 size char array is dynamically allocated
  IPV4_HDR *v4hdr = (IPV4_HDR *) myMemoryAllocator.getMemory(sizeof(IPV4_HDR));
  // Do things 


That method was something I picked up in C class, not sure how real-life it is. This way your program can sort of handle it's own memory. Rather than always using new and delete you have your own little block to play with.
Last edited on
Topic archived. No new replies allowed.