A structure is a collection of data. For example an employee record may contain
- Name
- address
- hire date
- salary
The structure could be defined
struct
{
char name[32];
char address[64];
char hireDate[10];
double salary;
}
A union is the same location defined in different ways. For exxample
union
{
double dval;
int ival[2];
char cval[8];
};
will allow you enter a floating point number and display that number in it's raw integer or byte form. Below is a program I wrote a while back for just this purpose. It can also be used to define multiple definitions for the same structure. For example, if the first byte of each record is a record type, and each record type is a different format, you can read the entire record, test the type, and use values out of a union to process the data. If this is not clear, I'll put together a tutorial...
The following program is written for Borland. Change the
getche() into an appropriate form for your compiler. I recommend the
fgets() form. The
if will also need a change.
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
int main()
{
int ch;
int i;
char buf[50];
union
{
double dd;
float ff[2];
long ll[2];
int ii[2];
unsigned char cc[8];
} xx;
printf(" D- double \n");
printf(" F- float \n");
printf(" L- long \n");
printf(" I- integer \n");
printf(" C- character\n");
printf(" x- exit \n");
while (ch != 0x1B)
{
xx.dd = 0.0L;
printf("What would you like to enter? ");
ch = getche();
ch = toupper(ch);
printf("\n");
switch(ch)
{
default:
ch = 0;
break;
case 'X':
ch = 0x1B;
case 0x1B:
break;
case 'D':
printf("Enter a double: ");
fgets(buf, 50, stdin);
sscanf(buf, "%lf", &xx.dd);
break;
case 'F':
printf("Enter a float: ");
fgets(buf, 50, stdin);
sscanf(buf, "%f", &xx.ff[0]);
break;
case 'L':
printf("Enter a long: ");
fgets(buf, 50, stdin);
sscanf(buf, "%ld", &xx.ll[0]);
break;
case 'I':
printf("Enter an int: ");
fgets(buf, 50, stdin);
sscanf(buf, "%d", &xx.ii[0]);
break;
case 'C':
printf("Enter a char: ");
fgets(buf, 50, stdin);
sscanf(buf, "%c", &xx.cc[0]);
break;
}
if (ch != 0x1B && ch != 0x00)
{
printf("\n");
printf("double: %15.5lf \n", xx.dd);
printf("float: %15.5f %15.5f \n", xx.ff[0], xx.ff[1]);
printf("long: %15ld %15ld \n", xx.ll[0], xx.ll[1]);
printf("int: %15d %15d \n", xx.ii[0], xx.ii[1]);
printf("char: ");
for (i=0; i < 8; i++)
{
if (i == 4) printf(" ");
printf ("%02X ", xx.cc[i]);
}
printf("\n");
printf("\n");
}
}
return 0;
}