MAP

Structures in c language


Simple Structures

A structure is a collection of one or more variables types grouped under a single name for easy manipulation. The variables in a structure, unlike those in an array, can be of different variable types. A structure can contain any of C's data types, including arrays and other structures. Each variable within a structure is called a member of the structure.

 

Text Box: struct tag 
{
    structure_member(s);
    /* additional statements may go here */
} instance;

The struct Keyword

 

Text Box: Struct student
{
    int no;
    char nm[5];
    float per;	
};
struct student S1;

Defining and Declaring Structures


The struct keyword is used to declare structures. A structure is a collection of one or more variables (structure_members) that have been grouped under a single name for easy man-ipulation. The variables don't have to be of the same variable type, nor do they have to be simple variables. Structures also can hold arrays, pointers, and other structures.The keyword struct identifies the beginning of a structure definition. It's followed by a tag that is the name given to the structure. Following the tag are the structure members, enclosed in braces. An instance, the actual declaration of a structure, can also be defined. If you define the structure without the instance, it's just a template that can be used later in a program to declare structures. Here s1 is student kind of variable which has 3 members no,name and per.

    NO                                      NAME                                                                        Per
 2 Bytes                                   5 Bytes                                                                        4 Bytes












Text Box: Struct student
{
    int no;
    char nm[5];
    float per;	
}S1,S2;

2001    2002        2003     2004       2005   2006       2007       2008        2009       2010        2011              

These statements define the structure type student  and declare two structure variable S1 and S2 of type studnet. S1 and S2 are each instances of type student Each structure variable contains 3 members no, name and per.

Accessing Structure Members

Individual structure members can be used like other variables of the same type. Structure members are accessed using the structure member operator (.), also called the dot operator, between the structure name and the member name. Thus variable s1 can be access in following way
S1.no=10;
S1.name=”AMAR”;
S1.per=80;
 
To display the screen locations stored in the structure variable s1, you could write

printf("%d,%s,%f", s1.no, s1.name,s1.per);

At this point, you might be wondering what the advantage is of using structures rather than individual variables. One major advantage is that you can copy information between structures of the same type with a simple equation statement. Continuing with the preceding example, the statement
 
S2 = S1;
is equivalent to this statement:
S2.no=S1.no=;
S2.name=S1.name;
S2.per=S1.per;

When your program uses complex structures with many members, this notation can be a great time-saver. Other advantages of structures will become apparent as you learn some advanced techniques. In general, you'll find structures to be useful whenever information of different variable types needs to be treated as a group. For example, in a mailing list database, each entry could be a structure, and each piece of information (name, address, city, and so on) could be a structure member.

 

Example 1
 
Text Box: struct SSN 
{
    int first_three;
    char dash1;
    int second_two;
    char dash2;
    int last_four;
}
/* Declare a structure template called SSN */
 
 
/* Use the structure template */
struct SSN customer_ssn;
Example 2
 
Text Box: struct date 
{
    char month[2];
    char day[2];
    char year[4];
} cur_date;
/* Declare a structure and instance together */
 
Example 3
 
Text Box: struct time
 {
    int hours;
    int minutes;
    int seconds;
} time_of_birth = { 8, 45, 0 };
/* Declare and initialize a structure */
 

Arrays of Structures

Text Box: struct entry
{
    char fname[10];
    char lname[12];
    char phone[8];
};

If you can have structures that contain arrays, can you also have arrays of structures? You bet you can! In fact, arrays of structures are very powerful programming tools. Here's how it's done. You've seen how a structure definition can be tailored to fit the data your program needs to work with. Usually a program needs to work with more than one instance of the data. For example, in a program to maintain a list of phone numbers, you can define a structure to hold each person's name and number:
 
A phone list must hold many entries, however, so a single instance of the entry structure isn't of much use. What you need is an array of structures of type entry. After the structure has been defined, you can declare an array as follows:
 
struct entry list[1000];
This statement declares an array named list that contains 1,000 elements. Each element is a structure of  type entry and is identified by subscript like other array element types. Each of these structures has three elements, each of which is an array of type char. This entire complex creation is diagrammed in When you have declared the array of structures, you can manipulate the data in many ways. For example, to assign the data in one array element to another array element, you would write
 
list[1] = list[5];
This statement assigns to each member of the structure list[1] the values contained in the corresponding members of list[5]. You can also move data between individual structure members. The statement
 
strcpy(list[1].phone, list[5].phone);
copies the string in list[5].phone to list[1].phone. If you want to, you can also move data between individual elements of the structure member arrays:
 
list[5].phone[1] = list[2].phone[3];
This statement moves the second character of list[5]'s phone number to the fourth position in list[2]'s phone number. (Don't forget that subscripts start at offset 0.)
Listing 11.3 demonstrates the use of arrays of structures. Moreover, it demonstrates arrays of structures that contain arrays as members.
 
Text Box: #include <stdio.h>
  /* Define a structure to hold entries. */
  struct entry 
{
   char fname[20];
   char lname[20];
   char phone[10];
 };
 /* Declare an array of structures. */
 struct entry list[4];
 int i;
 main()
 {
    /* Loop to input data for four people. */
     for (i = 0; i < 4; i++)
     {
         printf("\nEnter first name: ");
        scanf("%s", list[i].fname);
         printf("Enter last name: ");
        scanf("%s", list[i].lname);
         printf("Enter phone in 123-4567 format: ");
         scanf("%s", list[i].phone);
     }
     /* Print two blank lines. */
     printf("\n\n");
     /* Loop to display data. */
     for (i = 0; i < 4; i++)
     {
         printf("Name: %s %s", list[i].fname, list[i].lname);
         printf("\t\tPhone: %s\n", list[i].phone);
     }
     return 0;
 }
Example
 
 

Pointer To Structure

Text Box: # include<stdio.h>
Void main()
{
	struct emp
	{
		int empno;
		char nm[20];
		float sal;
};

struct emp e1={10,”RAJ”,10000};
Struct emp *p;
P=&e1;
Printf(“%d %s %f”,e1.empno,e1.nm,e1.sal);
Printf(“%d %s %f”,pà empno,pà nm,pàsal);
}

We can also address or point the structure variable with structure pointer itself. Also we can access the members of structure variable with the pointer variable

The à operator is used to refer to the structure elements with pointer.

Passing Structures as Arguments to Functions

Like other data types, a structure can be passed as an argument to a function. Listing 11.5 shows how to do this. This program is a modification of the program shown in Listing 11.2. It uses a function to display data on the screen, whereas Listing 11.2 uses statements that are part of main().
 
 
Text Box: #include <stdio.h>
 /* Declare and define a structure to hold the data. */
  struct data
 {
      float amount;
      char fname[30];
      char lname[30];
  } rec;
void print_rec(struct data x)
 {
    printf("\nDonor %s %s gave $%.2f.\n", x.fname, x.lname,x.amount);
 }
Example
 
 /* The function prototype. The function has no return value, */
 /* and it takes a structure of type data as its one argument. */
 
 
Text Box: main()
 {
   /* Input the data from the keyboard. */
    printf("Enter the donor's first and last names,\n");
    printf("separated by a space: ");
    scanf("%s %s", rec.fname, rec.lname);
    printf("\nEnter the donation amount: ");
    scanf("%f", &rec.amount);
     /* Call the display function. */
     print_rec( rec );
     return 0;
 }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More