Adding to other answers:
This code is illegal because ANSI C. ptr->q_count = htons(1); violates the rule of strict smoothing.
It is allowed to use unsigned short lvalue (i.e. the expression ptr->q_count ) to access memory that either does not have a declared type (for example, malloc 'd space), or declared a type of short or unsigned short or compatible.
To use this code as is, you must pass -fno-strict-aliasing to gcc or clang. Other compilers may or may not have a similar flag.
An improved version of the same code (which also has some forward compatibility with resizing the structure):
struct dns_header d = { 0 }; d.q_count = htons(1); unsigned char *buffer = (unsigned char *)&d;
This is legal because a strict alias rule allows an unsigned char alias to do nothing.
Note that buffer is not used in this code. If your code is actually a smaller piece of larger code, then buffer can be defined differently. In any case, it can be combined with d .
source share