C Language Structures and Unions

C Language Structures and Unions

Introduction to structures:

The C structure allows you to wrap variables with different data types into one single entity to make it easier for you to manipulate data. When you design a program, it is important step to choose a good way to represent the data that the program processes. In simple cases, variables and arrays are good enough. However in most scenarios, you need a new form of variable that reflects the real world. In addition, this new form has to be easier for you to manipulate it. For example, in your program, you may want to refer to address that holds multiple data it may contains like house number, street, zip code, state and country.  C language provides you a special kind of variable called structure. C structure allows you to wrap one or more variables with different data types into one. A structure can contain any valid data types like int, char, float, array or even other structures. Each variable in structure is known as a structure member.

Defining a structure:
 

Structure declarations are somewhat more complicated than array declarations, since a structure must be defined in terms of its individual members. In general terms, the composition of a structure may be defined as
struct tag {
member 1;
member 2;
…….
member m;
};
In this declaration, struct is a required keyword; tag is a name that identifies structures of this type (i.e., structures having this composition); and member 1, member 2,…, member m are individual member declarations.
The individual members can be ordinary variables, pointers, arrays, or other structures. The member names within a particular structure must be distinct from another, though a member name can be the same as the name of a variable that is defined outside the structure. A storage class, however, cannot be assigned to an individual member, and individual members cannot be initialized within a structure type declaration.
 

Example:
 

struct account
{
int acct_no;
char acct_type;
char name [80];
float balance;
};
Once the composition of a structure has been defined, individual structure-type variables can be declared as follows:
storage-class struct tag variable 1, variable 2, …., variable n;
Where storage-class is an optional storage class specifier, struct is a required keyword, tag is the name that appeared in the structure declaration, and variable 1, variable 2, …, variable n are structure variables of type tag.
You can declare variables of a structure type when you define the structure type by putting the variable names after the closing brace of the structure definition, but before the final semicolon. You can declare more than one such variable by separating the names with commas.
struct point
{
int x, y;
}
first_point, second_point;
That example declares two variables of type struct point, first_point and second_point.
You can declare variables of a structure type after defining the structure by using the struct keyword and the name you gave the structure type, followed by one or more variable names separated by commas.
struct point
{
int x, y;
};

struct point first_point, second_point;

That example declares two variables of type struct point, first_point and second_point.

struct with pointers:
The beginning address of a structure can be accessed in the same manner as any other address, through the use of the address (&) operator. Thus, if variable represents a structure-type variable, then &variable represents the starting point of that variable. Moreover, we can declare a pointer variable for a structure by writing
type *ptvar;
Where type is a data type that identifies the composition of the structure, and ptvar represents the name of the pointer variable. We can assign the beginning address of a structure variable to this pointer by writing
ptvar = &variable;
To access the members of a structure using a pointer to that structure, you must use the -> operator as follows:
struct_pointer->title;
 

Consider an example to access structure's member through pointer.
#include <stdio.h>
struct name
{
   int a;
   float b;
};
int main()
{
    struct name *ptr,p;
    ptr=&p;            /* Referencing pointer to memory address of p */
    printf ("Enter integer: ");
    scanf ("%d",&(*ptr).a);
    printf ("Enter number: ");
    scanf ("%f",&(*ptr).b);
    printf ("Displaying: ");
    printf ("%d%f",(*ptr).a,(*ptr).b);
    return 0;
}
In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can be accessed.
Structure pointer member can also be accessed using -> operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b

struct with arrays:
You can create an array of a structure type just as you can an array of a primitive data type.
     struct point
       {
         int x, y;
       };
     struct point point_array [3];
That example creates a 3-element array of struct point variables called point_array. You can also initialize the elements of a structure array:
     struct point point_array [3] = { {2, 3}, {4, 5}, {6, 7} };
As with initializing structures which contain structure members, the additional inner grouping braces are optional. But, if you use the additional braces, then you can partially initialize some of the structures in the array, and fully initialize others:
     struct point point_array [3] = {{2}, {4, 5}, {6, 7}};
In that example, the first element of the array has only its x member initialized. Because of the grouping braces, the value 4 is assigned to the x member of the second array element, not to the y member of the first element, as would be the case without the grouping braces.
After initialization, you can still access the structure members in the array using the member access operator. You put the array name and element number (enclosed in brackets) to the left of the operator, and the member name to the right.
     struct point point_array [3];
     point_array[0].x = 2;
     point_array[0].y = 3;

struct with functions:
Since structures are of custom data types, functions can return structures and also take them as arguments. Keep in mind that when you do this, you are making a copy of the structure and all its members so it can be quite memory intensive.
To return a structure from a function declares the function to be of the structure type you want to return. In our case a function to initialize our object structure might look like this:
        struct object createobj(char id[], int xpos, int ypos)
{
          struct object newobj;
          strcpy (newobj.id, name);
          newobj.xpos = xpos;
          newobj.ypos = ypos;
          return newobj;
 }
In C, structure can be passed to functions by two methods:
•    Passing by value (passing actual value as argument)
•    Passing by reference (passing address of an argument)
Passing structure by value:
A structure variable can be passed to the function as an argument as normal variable. If structure is passed by value, change made in structure variable in function definition does not reflect in original structure variable in calling function.
Passing structure by reference:
The address location of structure variable is passed to function while passing it by reference. If structure is passed by reference, change made in structure variable in function definition reflects in original structure variable in the calling function.
void printobj (struct object obj)
{
          printf (name: %s, obj.id);
          printf (x position: %d, obj.xpos);
          printf (y position: %d, obj.ypos);
          printf (\n);
        }

Enum & Typedef:
The typedef feature allows users to define new data-types that are equivalent to existing data types. Once a user-defined data type has been established, then new variables, arrays, structures, etc. can be declared in terms of this new data type. In general terms, a new data type is defined as typedef   type   new-type;
Where type refers to an existing data type and new-type refers to the new user-defined data type. It should be understood, however, that the new data type will be new in name only. Here is a simple declaration involving the use of typedef.
typedef   int   age;
In the declaration age is a user-defined data type, which is equivalent to type int.
The typedef feature is particularly convenient when defining structures, since it eliminates the need to repeatedly write struct tag whenever a structure is referenced. Hence, the structure can be referenced more concisely. In addition, the name given to the user-defined structure type often suggests the purpose of a structure within the program. In general terms, a user-defined structure type can be written as
typedef struct
{
    member 1;
    member 2;
    ………….;
   member m;
} new-type;
 

Where new-type is the user-defined structure type. Structure variables can then be defined in terms of the new data type.
typedef struct
{
        int acct_no;
        char acct_type;
        char name[80];
        float balance;
}   record;
record oldcustomer, newcustomer;
The first declaration defines record as a user-defined data type. The second declaration defines oldcustomer and newcustomer as structure variables of type record.
enum:
An enumeration is a data type, similar to a structure or a union. Its members are constants that are written as identifiers, though they have signed integer values. These constants represent values that can be assigned to corresponding enumeration variables. In general terms, an enumeration may be defined as
enum tag {member 1, member 2, …. , member m};
Where enum is a required keyword, tag is a name that identifies enumerations having this composition; and member 1, member 2,…., member m represents the individual identifiers that may be assigned to variables of this type. The member names must differ from one another, and they must be distinct from other identifiers whose scope is the same as that of the enumeration. Once the enumeration has been defined, corresponding enumeration variables can be declared as
storage-class enum tag variable 1, variable 2,……, variable n;
where storage-class is an optional storage class specifier, enum is a required keyword, tag is the name that appeared in the enumeration definition, and variable 1, variable 2, …… , variable n are enumeration variables of type tag. The enumeration definition can be combined with the variable declarations, as indicated and the tag is optional in this situation.
storage-class enum tag {member 1, member 2, …… ,member m} variable 1, variable 2, …… , variable n;

Arrays, strings as structure members:
 

As we are aware of the fact that the structures in the C language provides a mechanism to incorporate different data types within a same structure like integers, floats and character values which are known as structure members. As a fact, structures are simple to define if there are only one or two elements but in case if too many objects are needed e.g., to show the data of each student of a class, in that case we introduces the concept of the array of the structures. We can declare an array of structures as follows:
 

#include <stdio.h>
struct studentinfo
{
int rollno.;
char name [21];
char sex;
};
studentinfo detail[35];
 

In the above declaration, we have defined a structure named studentinfo which keeps the information about a particular student like rollno of the student, name and sex. Then after defining the structure we have declared an array of structures we can contain 35 objects of such structure and can incorporate the details of 35 students.
An array of structure can be initialized in the same manner as we initialize a simple array. It must be kept in mind that only the static and external variables are initialized.
 

Containership:
 

Containership is the ability of a class to contain the objects as member data. If a class is contained in another, container class does not have the ability to add and modify of contained. There is no difference between a class and a struct except that by default, the members of a struct are public, and the members of a class are private. Also structs are by default inherited publicly. For example, class A could contain an object of class B as a member. Here, all the public methods (or functions) defined in B can be executed within the class A. Class A becomes the container, while class B becomes the contained class. Containership is also referred to as Composition. In this example, it can be said that class A is composed of class B. In OOP, Containership represents a “has-a” relationship. It is important to note that, even though the container has access to execute all the public methods of the contained class, it is not able to alter or provide additional functionality. When it comes to a real world programming problem, an object of class Textbox may be contained in the class Form, and thus can be said that a Form contains a Textbox.

Unions:
 

Unions, like structures, contain members whose individual data types may differ from one another. However, the members within a union all share the same storage area within the computer’s memory, whereas each member within a structure is assigned its own unique storage area. Thus, unions are used to save the memory. They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time.
Within a union, the bookkeeping required to store members whose data types are different is handled automatically by the compiler. However, the user must keep track of what type of information is stored at any given time. An attempt to access the wrong type of information will produce meaningless results. In general terms, the composition of a union may be defined as

union tag
{
member 1;
member 2;
………….
member m;
};
Where union is a required keyword and the other terms have the same meaning as in structure definition. The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:
union Data
{
   int i;
   float f;
   char str [20];
} data; 
Now a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable i.e. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union.

Difference between structure and union:
 

•    We can access all the members of a structure at any time and only one member of union can be accessed at any time.
•    Memory is allocated for all variables and in case of unions, allocates memory for a variable which require more memory.
•    All members can be initialized in case of structures whereas only the first member can be initialized in union.
•    struct keyword is used to declare structure and union keyword is used to declare union.

0 comments:

Post a Comment