• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1456
  • Last Modified:

struct and union question

Im trying to learn directx, and the book Im using has a structure that looks like this:

typedef struct VECTOR2D_TYP
{
  union
  {
    float M[2];
 
    struct
    {
      float x,y;
    }; // end struct

  }; // end union

} VECTOR2D;

Now I have a vague idea of what a union does.  It allows different variables to share the same address space.  The problem is I dont know what is going on with the code above.  I'm guessing the float array, and the structure share the same space.  How would you access the two float variables (x,y) in that structure though, and what is the reasoning behind the union?
0
lwinkenb
Asked:
lwinkenb
2 Solutions
 
sunnycoderCommented:
How would you access the two float variables (x,y) in that structure though

#include <stdio.h>

 typedef struct VECTOR2D_TYP
        {
                 union
                          {
                                     float M[2];

                                        struct
                                                   {
                                                                float x,y;
                                                                   }; // end struct

                                         }; // end union

        } VECTOR2D;

int main ()
{
        VECTOR2D a;

        a.x = 1.0;
        a.y= 2.0;

        printf ( "%f %f",a.x,a.y);
}
0
 
sunnycoderCommented:
ideally, you should be having name for that struct .... makes things easier

concept of a union

Simply stated, a union allows you a way to look at the same data with different types, or to use the same data with different names.

In this example we have two elements to the union, the first part being the integer named value, which is stored as a two byte variable somewhere in the computers memory. The second element is made up of two character variables named first and second. These two variables are stored in the same storage locations that value is stored in, because that is what a union does. A union allows you to store different types of data in the same physical storage locations. In this case, you could put an integer number in value, then retrieve it in its two halves by getting each half using the two names first and second. This technique is often used to pack data bytes together when you are, for example, combining bytes to be used in the registers of the microprocessor.

Accessing the fields of the union are very similar to accessing the fields of a structure

from::: http://pesto.csc.calpoly.edu/~kvoelker/c/ctutorials/c-tutorial_dodrill/CHAP11.HTM
WHAT ARE UNIONS?

union1.c

#include

int main()
{
   union
   {
      int value;     /* This is the first part of the union        */
      struct
      {
         char first; /* These two values are the second part of it */
         char second;
      } half;
   } number;

long index;

   for (index = 12 ; index < 300000L ; index += 35231L)
   {
      number.value = index;
      printf("%8x %6x %6x\n", number.value,
                            number.half.first, number.half.second);
   }

   return 0;
}



/* Result of execution on a 16 bit system

       c      c      0
    89ab   ffab   ff89
    134a     4a     13
    9ce9   ffe9   ff9c
    2688   ff88     26
    b027     27   ffb0
    39c6   ffc6     39
    c365     65   ffc3
    4d04      4     4d

*/

Examine the file named UNION1.C for an example of a union. Simply stated, a union allows you a way to look at the same data with different types, or to use the same data with different names.

In this example we have two elements to the union, the first part being the integer named value, which is stored as a two byte variable somewhere in the computers memory. The second element is made up of two character variables named first and second. These two variables are stored in the same storage locations that value is stored in, because that is what a union does. A union allows you to store different types of data in the same physical storage locations. In this case, you could put an integer number in value, then retrieve it in its two halves by getting each half using the two names first and second. This technique is often used to pack data bytes together when you are, for example, combining bytes to be used in the registers of the microprocessor.

Accessing the fields of the union are very similar to accessing the fields of a structure and will be left to you to determine by studying the example.

One additional note must be given here about the program. When it is run using some C compilers, the data will be displayed with leading f's due to the hexadecimal output promoting the char type variables to int and extending the sign bit to the left. Converting the char type data fields to int type fields prior to display should remove the leading f's from your display. This will involve defining two new int type variables and assigning the char type variables to them. This will be left as an exercise for you. Note that the same problem will come up in a few of the later files in this tutorial.

Compile and execute this program and observe that the data is displayed as an int and as two char variables. The char variables may be reversed in order because of the way an int variable is stored internally in your computer. If your system reverses these variables, don't worry about it. It is not a problem but it can be a very interesting area of study if you are so inclined.

0
 
gagandeep_1984Commented:
Dear friend (lwinkenb),

To access the float variables, you would first need to go through the structure name " VECTOR2D" and than to union name, suppose "xy". There is a structure declared inside the union and I am taking its name as "st". So, the code to access the x float variable  VECTOR2D.xy.st.x and to y float variable VECTOR2D.xy.st.y

Gagan..
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
grg99Commented:
I'd guess that in the example, smoetims you want to access the values with a subscript, and otehr times just by naming them as X or Y.

This is quite common in graphics operations. Sometimes in order to performa scaling or rotation, you have to do some math on the x and y values, but the value you want depends on some for() loop index.  For example, you may want to multiply the x,y pair by some other array of textures or rotation parameters, so you ned a loop like:  for(i=0;i<=1;i++)  forj=0;j<=1;j++) Result[i] = Matrix[ i, j] * Point[ i ];
That's when you'd like to use the float[2] version of the variable.

Most other times you want to refer to the variables as being x and y coordinates.;   Then you use the struct version of the variable naems.
0
 
lwinkenbAuthor Commented:
Thanks for the help, I think I understand now.

I have just one followup question for you sunny:
>>first part being the integer named value, which is stored as a two byte variable somewhere in the computers memory.

I was under the impression that an integer took up 4 bytes of memory.  Is it actually 2?
0
 
sunnycoderCommented:
>I  was under the impression that an integer took up 4 bytes of memory.  Is it actually 2?
there was a time when it took two bytes ... now it takes four ...
whenever in doubt, use sizeof(int) to get authentic results
0
 
lwinkenbAuthor Commented:
Thanks for all the help :)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now