Cast struct to array?
Your buffer
is simply a contiguous array of raw bytes. They have no semantic from the buffer
point of view: you cannot do something like buffer->ra = 1
.
However, from a struct dns_header *
point of view those bytes would become meaningful. What you are doing with ptr = (struct dns_header *) &buffer;
is mapping your pointer to your data.
ptr
will now points on the beginning of your array of data. It means that when you write a value (ptr->ra = 0
), you are actually modifying byte 0 from buffer
.
You are casting the view of a struct dns_header
pointer of your buffer
array.
The buffer is just serving as an area of memory -- that it's an array of characters is unimportant to this code; it could be an array of any other type, as long as it were the correct size.
The struct defines how you're using that memory -- as a bitfield, it presents that with extreme specificity.
That said, presumably you're sending this structure out over the network -- the code that does the network IO probably expects to be passed a buffer that's in the form of a character array, because that's intrinsically the sanest option -- network IO being done in terms of sending bytes.
Suppose you want to allocate space for the struct so you could
ptr = malloc(sizeof(struct dns_header));
which will return a pointer to the allocated memory,
ptr = (struct dns_header *) &buffer;
is almost the same, except that in this case it's allocated in the stack, and it's not necessary to take the address of the array, it can be
ptr = (struct dns_header *) &buffer[0];
or just
ptr = (struct dns_header *) buffer;
there is no problem in that though, because the addresses will be the same.