Structures in C

Structures in C Language

Data types are of two types primitive and non-primitive. Primitive data types are basic one and non-primitive data types are user defined data types. For example arrays, which are the data structures whose individual data elements are all of the same type. But data structure whose individual data elements differ in type and are logically related together are called structures .

The main use of structures is to bind together collections of different types of variables (elements) that are logically related to each other, so they can easily be treated as a single unit. The individual elements of a structure are known as its members or fields.

Members of a structure can be

  • Variables, pointer variables, arrays and other data structures.
  • A pointer to the variable of the type of structure itself

But, members cannot be

  • The variables of the type of structure itself

Structures are used in the applications that need user-defined types, such as windows, databases, and graphics.

Defining a structure

A structure must be defined in terms of the members it contains. There are many formats for defining a new data type using a structure. The first one is

  struct emp
   {
        char name [25]
         int age;
        float salary;
} ;
  • This declares a structure ( or a new data type) called person, that is created using the keyword struct.
  • emp is just a tag for the structure that serves as shorthand for future declarations. This tag is optional.
  • Members or fields of a structure can be of any type ( pointers, arrays , and other structures whose types do not have the same name as emp). In the structure declared above, we have three members : an array called name, an integer age, and a float salary.
  • The semicolon(;) at the end indicates the end of the definition of the new data type called struct emp.

The above declaration does not allocate any storage, and only specifies the format ( or template) of a new data type called struct emp. The actual storage is allocated when we declare variables of this new type as shown below :

  struct emp e1, e2;

This declaration tells C compiler to allocate storage for two variables e1 and e2 of type struct emp. Each variable must occupy storage of 31 bytes (25 bytes for name + 2 bytes for age + 4 bytes for salary).

The second format for defining a new data type using structure is,

       struct emp
       {
            char name [25] ;
            int age;
            float salary;
       }e1, e2;
  • In this format, we create a new type struct emp and also define two variables (e1 and e2) of its type, in a single shot.
  • The difference between this format and the previous one is that, in this format the memory is allocated to each variable in the definition itself, as the variables are defined along with the creation of the new type struct emp. In the previous format, memory was allocated when the statement –

   struct emp e1, e2;

This command is used to define two variables e1 and e2 of type struct emp.

Initializing the structures

We can initialize a structure using an initialize list. This list initializes each member of a structure variable to some initial value, and is assigned to the structure variable after being enclosed between a pair of braces. For example.

 
struct person
{
    char name[25];
    int age;
    float salary;
};
struct person p1 = {“Ram”, 25, 15000}, p2 = {“Vikas”, 31, 20000};

Here two structure variables p1 and p2 are initialized using the initializer list. The initialization of a structure variable consists of initializing  its every member to some initial value. For example, the structure variable p1 is initialized as

   p1={“Ram” ,25,15000};

Which means that the member name of p1 is initialized to “Ram”, the member age of p1 is initialized to 29, and the member salary of p1 is initialized to 15000. Similar initialization is done to the structure variable p2.

The above thing can also be written in a single shot as,

  
struct person
{
    char name[25];
    int age;
    float salary;
}p1= {“Ram”,25,15000.00}, p2={“Vikas”,31,20000.00};

Untagged structures

It is also possible to use structures without any tag. Untagged structures are used to declare the variables of its type in the definition of the structure itself, as in

    
struct /* a structure without any tag */
{
    char name[25];
    int age;
    float salary;

} p1, p2;
 /* variables of untagged structure type can be declared here only */

So, we cannot  declare additional variables of the untagged structure. We can only declare the variables of an untagged structure in the definition of the untagged structure itself.

Use of typedef with struct

Typedef is used to give a new name to an existing type, and this name can then be used to declare the variables of that type. Typedef is used to shorten the declaration of complex data types and give them more meaningful names. So, we can use typedef while defining a structure, with or without a tag. For example,

With tag

typedef struct person            /* here, we are using the tag person */

    {

  ...

    } person;
                      /* now, Person is same as struct person */

    person p1,p2;
     /* same as, struct person p1, p2 ; , but is more meaningful */

 

                           OR

struct person

{

        ...
};

typedef struct person Person;
          /* Use person in place of struct person */

    Person p1,
    p2;
           /* Person is more convenient and meaningful than struct person */

Without tag

typedef struct

{

       ...

} Person;
                      /* still now, Person represents the structure */

    Person p1,p2;
              /* and the variables are declared using person */

Usually we do not need tag and typedef both at the same time in the structure declarations. They are both used together only when we define self-referential structures.

To access the members of a structure

Structure members are accessed using the member selection operators . (dot) and -> (arrow)

Let us define a structure as,

struct person
{
      char name[25];
      int age;
    float salary;
};

 

Now, if we declare a variable of type struct person as

struct person p;

We can refer to the members of the variable p (of type struct person) as

  1. name
  2. age
  3. salary

and, if we declare a pointer to struct person as

struct person *px;

then, the members of the pointer to struct person can be referred as

  px->name

  px->age

  px->salary

the format px->name to refer to a member of a structure is actually a shorthand for a more complex format (*px).name. That is , we can also write the px->name, px->age, and px->salary as (*px).name, (*px).age, and (*px).salary respectively.

Example:

#include<stdio.h> 
struct person
 { 
   char name[25]; 
   int age;  
   float salary; 
 }; 
 typedef struct person Person;   
/* now, struct person means Person only*/ 
void main() 
  {  
    Person first; /* first is a variable of person type */ 
    Person *second; /* second is a pointer to person type */ 
    second=&first; /* make second to point to first */ 
    printf(“Enter first person’s name, age , and salary :”); 
    scanf(“%s %d %f “,&first.name,&first.age,&first.salary); 
    printf(“The first person’s name is %s, age is %d,and salary is %f \n”,first.name,first.age,first.salary); 
    printf(“through second, the first person’s name is %s,age is %d ,and salary is %f\n”,second->name,second-         >age,second->salary); 
  }

Embedding of structures

We can have one structure as a member of the another structure. This is known as embedding of the structures. For example, in a graphics environment, the following structure declarations might be found :

typedef struct point
{
   int x;
   int y;
}Point;                               /* now, point is same a struct point */
typedef struct circle
{
  double radius;
  Point center;          /* embed a variable of point type in struct circle */
}circle;                      /* now on wards, circle is same as struct circle */

Further graphics structure declarations such as

typedef struct line

{

   Point start;      /* embed a point type variable start in struct line */

   Point end;       /* embed a point type variable end in struct line */

}Line;

and

typedef struct triangle

{

   Point pt [3] ;                    /* embed a point type array variable pt in struct triangle */

}Triangle;                   /* now on wards, Triangle is same as struct triangle */

Passing a structure to a function

We can pass a structure to a function in the same way we can pass a normal variable to a function. That is , either we can pass the structure by value, or by reference (address) as shown below :

Passing structure by value :

We are going to write a C program that implements rational numbers. A rational number is a number represented in the form

              Rational number = Numerator/Denominator

Example:

#include <stdio.h>
#include <conio.h>
typedef struct
{
    int num; /* numerator */
    int den; /* denominator*/
} Rational;
int gcd(int a, int b);                  /* to find greatest common divisor of 2 numbers */
Rational normalize(Rational r);         /* i.e. , 14/16 normalized = 7/8 ;  */
int compare(Rational r1, Rational r2);  /* to compare 2 Rational numbers */
Rational mul(Rational r1, Rational r2); /* to multiply 2 Rational numbers */
void print(Rational r);                 /* to display a Rational number */
void main()
{
    Rational r1, r2, r3;
    clrscr();
    printf(“Enter the numerator and denominator of 1st rational no
           :”);
  scanf (“%d %d",&r1.num,&r1.den);
  printf(“Enter the numerator & denominator of 2nd  rational no :”);
scanf(“%d %d”,&r2.num,&r2.den) ;
printf(“The rational numbers entered by you are :”) ;
print(r1);
print(r2) ;
if(compare(r1,r2)==1)
printf(“Both the rational numbers are equal \n”) ;
printf(“\n\n Their multiplication is :”);
r3=mul(r1,r2);
print(r3) ;
getch();
}
int gcd(int a, int b)
{
    int rem;
    while (b != 0)
    {
        rem = a % b;
        a = b;
        b = rem;
    }
    return a;
}
Rational normalize(Rational r)
{
    int a, b, rem;
    if (r.num > r.den)
    {
        a = r.num;
        b = r.den;
    }
    else
    {
        a = r.den;
        b = r.num;
    }
    a = gcd(a, b);
    r.num /= a;
    r.den /= a;
    return r;
}
int compare(Rational r1, Rational r2)
{
    r1 = normalize(r1);
    r2 = normalize(r2);
    if (r1.num == r2.num && r1.den == r2.den)
        return 1;
    else
        return 0;
}
Rational mul(Rational r1, Rational r2)
{
    Rational r3;
    r3.num = r1.num * r2.num;
    r3.den = den * r2.den;
    r3 = normalize(r3);
    return r3;
}
void print(Rational r)
{
    printf(“\n % 3d\n”, r.num);
    printf(“-- --\n”);
    printf(“% 3d\n”, r.den);
}

In the program rational  . c, we implement passing structures by values in the functions normalize() , compare( ), mul( ) , and print().

Now we will write the C functions, implementing “passing structure by value” mechanism, to

  • Give the area of a circle, and
  • To determine whether a given point lies inside a circle
#define square(x) (x)*(x) 
#define PI 3.14 
typedef struct point
{
    int x;
    int y;
}Point;
/*now, point is same as struct point */ 
typedef struct circle
{
    double radius;
    Point center;
    /*embed a member of point type in struct circle */
} Circle;
/*now, circle is same as struct circle */ 
double area(Circle c);
/* to  find area of the Circle c */ 
incircle(Point p, Circle c);
/* to see if  point p lies inside the circle c */ 
void main()
{
    Point p = {10, 20};
    Circle c = {10.5, {5, 10}};
    printf(“The area of the circle is = % lf “, area(c));
    if (incircle(p, c))
        printf(“Point is inside the circle. “);
    else
        printf(“point is outside the circle.”);
}
double area(Circle c) 
{ 
    return PI * square(c.radius);
}
incircle(Point p, Circle c)
{
    int dx, dy;
    dx = p.x–c.center.x;
    dy = p.y–c.center.y;
    return square(dx) + square(dy) <= square(c.radius);
}

 

 

Similarly  “passing a structure by reference (or, address)”, is carried out.

Pointer to a structure

A pointer to a structure type variable is same as a pointer to any other basic type of variable. It is created in the same way as a pointer to a basic type of variable is created. That is, if s is a  structure variable of type T, and ps is pointer to the variable s, we can denote this  relationship

As.

   T s;

   T *ps =&s;

For example, suppose we have a Date structure defined as :

typedef struct

{

   char day;

   char month;

  int year;

}date;

Then, we can declare a Date variable d and pointer to d ( say  pd ) as :

     Date d;

     Date *pd=&d;

Or, 

     Date d, * pd =&d;

In a single statement.

Now we can use this concept in the main program as :

#include<stdio.h>
main()
{
    struct
    {
        char day;
        char month;
        int year;
    } date;
    *ptr_date = &date;
    ptr_date->day = 22;
    ptr_date->month = 04;
    ptr_date->year = 2002;
    printf(“size of ptr_date = % d\n”, sizeof(ptr_date));
    printf("date is %2d: %02d:%2d\n”,date.day,date.month,date.year); 
    printf(“date is %2d:%02d:%2d\n”,ptr_date->day,ptr_date->month,ptr_date->year);
}

 

Output :

       Size of ptr_date=2

       Date is 22 : 04 : 2002

       Date is 22 : 04 : 2002

Array of structures

Like arrays of basic types, we can have arrays of structures ( which are use-defined types) also. An array of structure does things easy when it comes to read or write large amount of information. Example,

#include<stdio.h>
#define N 10
typedef struct
{
   char name [30];
   int age;
   float salary;
}Person;
vod main()
{
Person p[N];  /* an array of N (=10) structures of type person */
int i;
for(i=0;i<N;i++)
{
   printf(“Enter name:”);
   gets(p[i].name);
   printf(“Enter age:”);
   scanf(“%d”,&age);
   printf(“Enter salary");
   scanf(“%f”,&salary);
}
for(i=0;i<N;i++)
printf(“Name =%s\t Age=%d\t salary=%f\n”,p[i].name,p[i].age,p[i].salary);
}

Structures in C Language has been discussed in details. If you have any query please free to ask questions. If you like the topic share and comment on it.

Similar Topics:

You may also like :

Download Official TurboC Compiler from here

What are advantages of Structures?

·        A structure allows different data items, that are logically related together, to be combined together as a single unit.
·        Structures can be passed to, or returned from a function  while arrays cannot, even when both are aggregate types.
·        We can embed an array in a structure and then pass it to a function, or return it  from the function.
·        If any members of a structure are left uninitialized, they are all set to 0 (or blank space in case of a char type member).
·        One structure can be assigned to another if both of them have same name. This ensures that two different structures (that are meant for different purposes) cannot be mingled either accidentally or purposefully.
·        One structure can be nested inside another.
·        Structures can contain a member that is a pointer to the structure itself. These types of structures are known as self-referential structures and are very useful in building data structures like linked-lists, trees, graphs, stacks, queues, etc.

What are Disadvantages of Structures?

·        The size of structure must be known at compile time. So a structure’s size cannot be expanded or shortened as required (i.e. at run time).
The number of peripherals attached to a system may vary from system to system, in some systems they may be less but in others they may be more.
·        When a structure is passed to a function, its copy is sent to the corresponding argument of the function. Since function uses stack for this passing, passing a structure by value is costlier.  So, the structure must be kept as small as possible , or otherwise pass the structure by address (by using pointer).
·        Occupies more space in memory as compared to a union.

5 1 vote
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
3 years ago

[…] Structures in C […]

trackback
3 years ago

[…] Structures in C […]

trackback
3 years ago

[…] Recursion in C                        Bit Fields in C Language                          Structures in C […]

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via
Copy link
Powered by Social Snap