Assuming I have a structure such as:
typedef struct
{
char * string1;
char * string2;
} TWO_WORDS;
such that all the fields are of the same type, and my main has
TWO_WORDS tw;
can I reference string1 with tw[0] and string2 with two[1]? If so:
- is this part of the c standard?
- do i have to cast the struct to an array first?
- what about fields which are different sizes in memory
- what about fields which are different types but the same size?
- can you do pointer arithmetic within a structure?
–
I got pretty close with this construct:
As an example:
It is not guaranteed to work, as the compiler may add padding between fields. (Many compilers have a
#pragmathat will avoid padding of structs)To answer each of your questions:
is this part of the c standard? NO
do i have to cast the struct to an array first? YES
what about fields which are different sizes in memory
This can be done with even more “evil” casting and pointer-math
what about fields which are different types but the same size?
This can be done with even more “evil” casting and pointer-math
can you do pointer arithmetic within a structure?
Yes (not guaranteed to always work as you might expect, but a structure is just a piece of memory that you can access with pointers and pointer-math)