Structures

Although arrays greatly improved our ability to store data, there is one major drawback to their use … each element (each box) in an array must be of the same data type.  It is often desirable to group data of different types and work with that grouped data as one entity. We now have the power to accomplish this grouping with a new data type called a structure.

A structure is a collection of variable types grouped together. You can refer to a structure as a single variable, and to its parts as members of that variable by using the dot (.) operator. The power of structures lies in the fact that once defined, the structure name becomes a user-defined data type and may be used the same way as other built-in data types, such as int, double, char, etc. It also includes elements such as pointers, arrays and other structures.

Defining a Structure

Generally, all of the members of a structure are logically related. For example, the name and address information in a mailing list would normally be represented in a structure. The following code fragment shows how to declare a structure that defines the name and address fields. The keyword struct tells the compiler that a structure is being declared.

struct addr
{
char street[40];
char city[20];
char state[3];
unsigned long int zip;
};

 Note semicolon!!!!!!!!!!

addr is called the structure tag, and is your brand new data type, like int, double, char or float. street, city, state, zip are structure members.

Declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure. After declaring the structure, the next step is to define a structure variable.

How to declare Structure Variable?

This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name.

The most efficient method of dealing with structure variables is to define the structure globally.  This tells “the whole world”, namely main and any functions in the program, that a new data type exists.  To declare a structure globally, place it BEFORE int main().  The structure variables can then be defined locally in main, for example.

addr addr_info;

You may also declare one or more structure variables when you declare a structure. For example,
struct addr {
char street[40];
char city[20];
char state[3];
unsigned long int zip;
} addr_info, binfo, cinfo;

defines a structure type called addr and declares variables addr_info, binfo, and cinfo of that type. The variable names appear before the semicolon ending the structure declaration.  This method is useful only when you know how many variables of this type your program will be using.

If you only need one structure variable, the structure type name is not needed. That means that
struct {
char street[40];
char city[20];
char state[3];
unsigned long int zip;
} addr_info;

declares one variable named addr_info as defined by the structure preceding it. Note that the individual members cannot be initialized within a structure-type declaration. The member names within a particular structure must be distinct from one another but can be the same as the variable name that is defined outside the structure. A storage class cannot be assigned to an individual member because when a structure variable is declared, storage class is assigned to all the members of the structure.

What happens when structure is defined?

When structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 4 structure members. Char assigns 1 byte to a variable and unsigned long assigns 4 bytes to a variable. Therefore, street(40 bytes), city(20 bytes), state(3 bytes) and zip(4 bytes), are the components of the structure “addr” which will be allocated (40+20+3+4=)67 bytes in the memory after the structure variable is defined.

How to access structure members in C++?

Individual members of a structure are accessed through the use of the . operator (usually called the dot operator). For example, the following code assigns the ZIP code 12345 to the zip field of the structure variable addr_info declared earlier:
addr_info.zip = 12345;
The structure variable name followed by a period and the member name references that individual member. The general form for accessing a member of a structure is structure-name.member-name

Since street is a character array, you can access the individual characters of addr_info.street by indexing street. For example, you can print the contents of addr_info.street one character at a time by using the following code:
for(int i=0; addr_info.street[i]; i++)
cout << addr_info.street[i];

We can also initialize the entire structure while creating an instance of the structure for example:
addr addr_info = {"Gandhi road", "Las Vegas", "Canada"};

Nested structures

A structure variable may be defined as a member of another structure. The declaration of embedded structure must appear before the declaration of the outer structure. eg. structure addr is declared before structure student. We can write the structure student declaration as follows:

struct student
{
char name[20];
int studentID;
addr addr_info;
};

This structure type student can be rewritten as

struct student
{
char name[20];
int studentID;
struct addr {
      char street[40];
      char city[20];
      char state[3];
      unsigned long int zip;
      } addr_info;
}stud;

The following code fragment assigns 93456 to the zip element of addr.
stud.addr_info.zip = 93456;

Thus nested structures save time when writing programs that use similar structures. The common members have to be defined only once in their own structure and then use that structure as a member in another structure. Standard C++ specifies that structures may be nested to at least 256 levels.

Structure Assignments

The information contained in one structure may be assigned to another structure of the same type using a single assignment statement i.e. you do not need to assign the value of each member separately. The following program illustrates structure assignments:
struct {
int a;
int b;
} x, y;
x.a = 10;
y = x; /* assign one structure to another */

After the assignment, y.a will contain the value 10.

Arrays of Structures

Perhaps the most common usage of structures is in arrays of structures. To declare an array of structures, you must first define a structure and then declare an array variable of that type. For example, to declare a 100-element array of structures of type addr, defined earlier, write
addr addr_info[100];
This creates 100 sets of variables that are organized as defined in the structure addr. To access a specific structure, index the structure name. For example, to print the ZIP code of structure 3, write
cout << addr_info[2].zip;
Like all array variables, arrays of structures begin indexing at 0.

Passing Structures to Function

If you have a structure local to a function and you need to pass its values to another function , then it can be achieved in two ways :
(i) by passing individual structure elements
(ii) by passing the entire structure .
Both the ways can be achieved by call by value as well as by call by reference method of passing variables.

Passing Structure Members to Functions

When you pass a member of a structure to a function, you are actually passing the value of that member to the function. Therefore, you are passing a simple variable (unless, of course, that element is compound, such as an array). A single structure member can also be returned by the return statement. For example, consider this structure:

struct fred
{
char x;
int y;
float z;
char s[10];
} mike;

Here are examples of each member being passed to a function: 
func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */

If you wish to pass the address of an individual structure member, put the & operator before the structure name. For example, to pass the address of the members of the structure mike, write
func(&mike.x); /* passes address of character x */
func2(&mike.y); /* passes address of integer y */
func3(&mike.z); /* passes address of float z */
func4(mike.s); /* passes address of string s */
func(&mike.s[2]); /* passes address of character s[2] */

Remember that the & operator precedes the structure name, not the individual member name. Note also that s already signifies an address, so no & is required.

Passing entire structure to Functions

Passing entire structure makes the most sense when the structure is relatively compact. The entire structure can be passed to the function both ways by value and by reference. Passing by value is useful when the original values are not to be changed and passing by reference is useful when original values are to be changed. When using a structure as a parameter, remember that the type of the argument
must match the type of the parameter.

Structure Pointers

Like other pointers, structure pointers are declared by placing * in front of a structure variable’s name. For example, assuming the previously defined structure addr, the following declares addr_pointer as a pointer to data of that type:
addr *addr_pointer;

A structure member could be accessed by pointers with either of the following statements

addr *addr_info;
(*addr_info).zip=123456;
addr *addr_info;
addr_info -> zip = 123456;

The following panel summarizes possible combinations of the operators for pointers and for structure members:

Expression What is evaluated Equivalent
a.b Member b of object a  
a->b Member b of object pointed to by a (*a).b
*a.b Value pointed to by member b of object a *(a.b)

There are two primary uses for structure pointers: to pass a structure to a function using call by reference, and to create linked lists and other dynamic data structures that rely on dynamic allocation.


Unions

If we are having the less memory to use in our program, for example 64K, we can use a single memory location for more than one variable this is called union.

Defining a Union

Union can be defined by the keyword union.

union myUnion{
	int var1;
	long var2;
};

Here we have defined a union with the name myUnion and it has two members i.e. var1 of type int and var2 of type long

Declaring the Union

We can declare the union in various ways. By taking the above example we can declare the above defined union as.

union myUnion{
	int var1;
	long var2;
}newUnion;

So newUnion will be the variable of type myUnion. We can also declare the union as

myUnion newUnion;

Initializing the Union

We can initialize the union in various ways. For example

union myUnion{
	int var1;
	long var2;
}newUnion={10.5};

or we can initialize it as

newUnion.var1= 10;

In later stages we can also initialize the var2 as well but this will over write the var1 value. Normally when we declare the union it is allocated the memory that its biggest member can occupy. So here in our example newUnion will occupy the memory which a long type variable can occupy.


Source: C++ Complete Reference