Solved

struct and union question

Posted on 2003-11-16
7
1,447 Views
Last Modified: 2010-04-15
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
Comment
Question by:lwinkenb
7 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 200 total points
ID: 9758076
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9758089
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
 
LVL 1

Expert Comment

by:gagandeep_1984
ID: 9758796
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
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 
LVL 22

Assisted Solution

by:grg99
grg99 earned 50 total points
ID: 9758797
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
 
LVL 5

Author Comment

by:lwinkenb
ID: 9759386
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9761503
>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
 
LVL 5

Author Comment

by:lwinkenb
ID: 9762180
Thanks for all the help :)
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now