Users Online

· Guests Online: 55

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#C PROGRAMMING LANGUAGE TUTORIALS

Structures - C Programming


 

A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.

1. Declaring a Structure

The general form of a structure declaration statement is given below:

struct <structure name> 
{ 
    structure element 1; 
    structure element 2; 
    structure element 3; 
    ...... 
    ......  
    structure element n;
};

Once the new structure data type has been defined one or more variables can be declared to be of that type.

For example the variables b1, b2, b3 can be declared to be of the type struct book,

struct book 
{ 
    char name; 
    float price; 
    int pages; 
}; 

as,

struct book b1, b2, b3; 

This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in this case, 7 bytes — one for name, four for price and two for pages. These bytes are always in adjacent memory locations.

Like primary variables and arrays, structure variables can also be initialized where they are declared. The format used is quite similar to that used to initiate arrays.

struct book 
{ 
    char name[10]; 
    float price; 
    int pages; 
};
 
struct book b1 = { "Basic", 130.00, 550 } ; 
struct book b2 = { "Physics", 150.80, 800 } ;

2. Accessing Structure Elements

In arrays we can access individual elements of an array using a subscript. Structures use a different scheme. They use a dot (.) operator. So to refer to pages of the structure defined in book structure we have to use,

b1.pages 

Similarly, to refer to price we would use,

b1.price 

Note that before the dot there must always be a structure variable and after the dot there must always be a structure element.

3. Example

The following example illustrates the use of this data type.

#include<stdio.h> 
main() 
{ 
    struct book 
    { 
        char name; 
        float price; 
        int pages; 
    }; 
    struct book b1, b2, b3 ;
     
    printf("\nEnter names, prices & no. of pages of 3 books\n"); 
    scanf("%c %f %d", &b1.name, &b1.price, &b1.pages); 
    scanf("%c %f %d", &b2.name, &b2.price, &b2.pages); 
    scanf("%c %f %d", &b3.name, &b3.price, &b3.pages);
     
    printf("\n\nAnd this is what you entered"); 
    printf("\n%c %f %d", b1.name, b1.price, b1.pages); 
    printf("\n%c %f %d", b2.name, b2.price, b2.pages); 
    printf("\n%c %f %d", b3.name, b3.price, b3.pages); 
} 

And here is the output...

Enter names, prices and no. of pages of 3 books 
A 100.00 354 
C 256.50 682 
F 233.70 512 

And this is what you entered 
A 100.000000 354 
C 256.500000 682 
F 233.700000 512

4. Structures as Function Arguments

You can pass a structure as a function argument in the same way as you pass any other variable.

#include <stdio.h>
#include <string.h>
 
struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

/* function declaration */
void printBook( struct Books book );

int main( ) {

   struct Books Book1;        /* Declare Book1 of type Book */
   struct Books Book2;        /* Declare Book2 of type Book */
 
   /* book 1 specification */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Developer Insider"); 
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* book 2 specification */
   strcpy( Book2.title, "C++ Programming");
   strcpy( Book2.author, "Developer Insider");
   strcpy( Book2.subject, "C++ Programming Tutorial");
   Book2.book_id = 6495700;
 
   /* print Book1 info */
   printBook( Book1 );

   /* Print Book2 info */
   printBook( Book2 );

   return 0;
}

void printBook( struct Books book ) {

   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);
}

When the above code is compiled and executed, it produces the following result −

Book title : C Programming
Book author : Developer Insider
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : C++ Programming
Book author : Developer Insider
Book subject : C++ Programming Tutorial
Book book_id : 6495700

5. Summary

  • A structure is usually used when we wish to store dissimilar data together.
  • Structure elements can be accessed through a structure variable using a dot (.) operator.
  • Structure elements can be accessed through a pointer to a structure using the arrow (->) operator.
  • All elements of one structure variable can be assigned to another structure variable using the assignment (=) operator.
  • It is possible to pass a structure variable to a function either by value or by address.
  • It is possible to create an array of structures

6. Examples

 

EXAMPLE STATEMENT FOR STRUCTURE AND UNION IN C LANGUAGE

 

 

1. Calculate Size of Structure

 

/**********************************************************
 Statement - Calculate Size of Structure
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 **********************************************************/


#include<stdio.h>

struct stud {
    int roll;
    char name[10];
    int marks;
};

int main() {
    int size;
    struct stud s;
    
    size = sizeof(s);
    printf("nSize of Structure : %d", size);
    
    return(0);
}

/*
 Explanation :
 ---------------
 Structure is Collection of elements of the Different data Types.
 Size of the Structure Can be Evaluated using “sizeof Operator”
 
 size = sizeof(s);
 
 Formula for Calculating Size of Structure :
 -------------------------------------------
 Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)
 = 2 + 10 + 2
 = 14
 ->Size depends on your computer
 
 Remember :
 ----------
 sizeof is Operator not function
 sizeof Operator Takes any Variable as Parameter.
 */

 

 

2. Use structure within union

 

 

/**********************************************************
 Statement - Use structure within union
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 **********************************************************/


#include<stdio.h>
#include<conio.h>

void main() {
    struct student {
        char name[30];
        char sex;
        int rollno;
        float percentage;
    };
    
    union details {
        struct student st;
    };
    union details set;
    clrscr();
    
    
    printf("Enter details:");
    
    printf("\nEnter name : ");
    scanf("%s", set.st.name);
    printf("\nEnter roll no : ");
    scanf("%d", &set.st.rollno);
    
    flushall();
    
    printf("\nEnter sex : ");
    scanf("%c", &set.st.sex);
    printf("\nEnter percentage :");
    scanf("%f", &set.st.percentage);
    
    printf("\nThe student details are : \n");
    printf("\name : %s", set.st.name);
    printf("\nRollno : %d", set.st.rollno);
    printf("\nSex : %c", set.st.sex);
    printf("\nPercentage : %f", set.st.percentage);
    
    getch();
}

 

3. Find the size of a union

 

/**********************************************************
 Statement - Find the size of a union
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 **********************************************************/

#include <stdio.h>
#include <conio.h>

void main()
{
    union sample
    {
        int   m;
        float n;
        char  ch;
    };
    
    union sample u;
    clrscr();
    
    printf("The size of union =%d\n", sizeof(u));
    
    /*initialization */
    
    u.m = 25;
    printf("%d %f %c\n", u.m, u.n,u.ch);
    
    u.n = 0.2;
    printf("%d %f %c\n", u.m, u.n,u.ch);
    
    u.ch = 'p';
    printf("%d %f %c\n", u.m, u.n,u.ch);
    
    getch();
}    	/*End of main() */

/*-----------------------------------------
 Output
 The size of union =4
 25 12163373596672.000000 
 -13107 0.200000 Õ
 -13200 0.199999 p
 ------------------------------------------*/

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.72 seconds
10,272,216 unique visits