I was told that the 'union' keyword allows you to be able to assign two variables to the same block of memory, but I'm not sure how you use it, and I was hoping someone could tell me.
Thanks in advanced;
Printable View
I was told that the 'union' keyword allows you to be able to assign two variables to the same block of memory, but I'm not sure how you use it, and I was hoping someone could tell me.
Thanks in advanced;
What you say is correct and I once came across an example that demonstrated it as follows:
The example was to reverse the byte ordering of a long.
A long is 4 bytes which is equal to an array of 4 characters. So a solution was to create a union consisitng of a long and an array of 4 chars. These will be laid over one another in memory. Then assign a value to the long, the 4 bytes of this value will each take up one of the chars in the array. Then simply reverse the order of the chars in the array and you have successfully reversed the byte order of the long.