You are on page 1of 11

UNIT – 3 (Structures & Union)

C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.

 If you want to access structure members in C, structure variable should be declared.


 Many structure variables can be declared for same structure and memory will be
allocated for each separately.
 It is a best practice to initialize a structure to null while declaring, if we don’t assign
any values to structure members.
DIFFERENCE BETWEEN C VARIABLE, C ARRAY AND C STRUCTURE:
 A normal C variable can hold only one data of one data type at a time.
 An array can hold group of data of same data type.
 A structure can hold group of data of different data types and Data types can be int,
char, float, double and long double etc.
C Structure:
struct student
{
int a;
char b[10];
Syntax }

a = 10;
Example b = “Hello”;
C Variable:
Syntax: int a;
int Example: a = 20;

Syntax: char b;
char Example: b=’Z’;
C Array:
Syntax: int a[3];
Example:
a[0] = 10;
a[1] = 20;
a[2] = 30;
int a[3] = ‘\0’;

Syntax: char b[10];
Example:
char b=”Hello”;
BELOW TABLE EXPLAINS FOLLOWING CONCEPTS IN C STRUCTURE.
1. How to declare a C structure?
2. How to initialize a C structure?
3. How to access the members of a C structure?
Using normal variable Using pointer variable

Syntax: Syntax:
struct tag_name struct tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
struct student struct student
{ {
int  mark; int  mark;
char name[10]; char name[10];
float average; float average;
}; };

Declaring structure using normal Declaring structure using


variable: pointer variable:
struct student report; struct student *report, rep;

Initializing structure using


Initializing structure using pointer variable:
normal variable: struct student rep = {100, “Mani”, 99.5};
struct student report = {100, “Mani”, 99.5}; report = &rep;

Accessing structure members Accessing structure members


using normal variable: using pointer variable:
report.mark; report  -> mark;
report.name; report -> name;
report.average; report -> average;
EXAMPLE PROGRAM FOR C STRUCTURE:
This program is used to store and access “id, name and percentage” for one student. We can
also store and access these data for many students using array of structures. You can check
“C – Array of Structures” to know how to store and access these data for many students.

#include <stdio.h>
#include <string.h>
 
struct student
{
           int id;
           char name[20];
           float percentage;
};
 
int main()
{
           struct student record = {0}; //Initializing to null
 
           record.id=1;
           strcpy(record.name, "Raju");
           record.percentage = 86.5;
 
           printf(" Id is: %d \n", record.id);
           printf(" Name is: %s \n", record.name);
           printf(" Percentage is: %f \n", record.percentage);
           return 0;
}

USES OF STRUCTURES IN C:
1. C Structures can be used to store huge data. Structures act as a database.
2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size etc.
C – Array of Structures
As you know, C Structure is collection of different datatypes (variables) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is also
called as structure array in C.

EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:


This program is used to store and access “id, name and percentage” for 3 students. Structure
array is used in this program to store and display records for many students. You can store
“n” number of students record by declaring structure variable as ‘struct student record[n]“,
where n can be 1000 or 5000 etc.

#include <stdio.h>
#include <string.h>
 
struct student
{
     int id;
     char name[30];
     float percentage;
};
 
int main()
{
     int i;
     struct student record[2];
 
     // 1st student's record
     record[0].id=1;
     strcpy(record[0].name, "Raju");
     record[0].percentage = 86.5;
 
     // 2nd student's record        
     record[1].id=2;
     strcpy(record[1].name, "Surendren");
     record[1].percentage = 90.5;
 
     // 3rd student's record
     record[2].id=3;
     strcpy(record[2].name, "Thiyagu");
     record[2].percentage = 81.5;
 
     for(i=0; i<3; i++)
     {
         printf("     Records of STUDENT : %d \n", i+1);
         printf(" Id is: %d \n", record[i].id);
         printf(" Name is: %s \n", record[i].name);
         printf(" Percentage is: %f\n\n",record[i].percentage);
     }
     return 0;
}

OUTPUT:

Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
 Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
 Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
C – Passing struct to function
 A structure can be passed to any function from main function or from any sub
function.
 Structure definition will be available within the function only.
 It won’t be available to other functions unless it is passed to those functions by value
or by address(reference).
 Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 3 ways.

1. Passing structure to a function by value


2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY VALUE:
In this program, the whole structure is passed to another function by value. It means the
whole structure is passed to another function with all members and their values. So, this
structure can be accessed from called function. This concept is very useful while writing very
big programs in C.

#include <stdio.h>
#include <string.h>
 
struct student
{
            int id;
            char name[20];
            float percentage;
};
 
void func(struct student record);
 
int main()
{
            struct student record;
 
            record.id=1;
            strcpy(record.name, "Raju");
            record.percentage = 86.5;
 
            func(record);
            return 0;
}
 
void func(struct student record)
{
            printf(" Id is: %d \n", record.id);
            printf(" Name is: %s \n", record.name);
            printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:

Id is: 1
Name is: Raju
Percentage is: 86.500000
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
In this program, the whole structure is passed to another function by address. It means only
the address of the structure is passed to another function. The whole structure is not passed
to another function with all members and their values. So, this structure can be accessed
from called function by its address.

#include <stdio.h>
#include <string.h>
 
struct student
{
           int id;
           char name[20];
           float percentage;
};
 
void func(struct student *record);
 
int main()
{
          struct student record;
 
          record.id=1;
          strcpy(record.name, "Raju");
          record.percentage = 86.5;
 
          func(&record);
          return 0;
}
 
void func(struct student *record)
{
          printf(" Id is: %d \n", record->id);
          printf(" Name is: %s \n", record->name);
          printf(" Percentage is: %f \n", record->percentage);
}
OUTPUT:

Id is: 1
Name is: Raju
Percentage is: 86.500000
C – Nested Structure
 Nested structure in C is nothing but structure within structure. One structure can be
declared inside other structure as we declare structure members inside a structure.
 The structure variables can be a normal structure variable or a pointer variable to
access the data. You can learn below concepts in this section.
1. Structure within structure in C using normal variable
2. Structure within structure in C using pointer variable
1. STRUCTURE WITHIN STRUCTURE IN C USING NORMAL VARIABLE:
 This program explains how to use structure within structure in C using normal
variable. “student_college_detail’ structure is declared inside “student detail” structure in
this program. Both structure variables are normal structure variables.
 Please note that members of “student_college_detail” structure are accessed by 2
dot(.) operator and members of “student detail” structure are accessed by single dot(.)
operator.

#include <stdio.h>
#include <string.h>
 
struct student_college_detail
{
    int college_id;
    char college_name[50];
};
 
struct student_detail
{
    int id;
    char name[20];
    float percentage;
    // structure within structure
    struct student_college_detail clg_data;
}stu_data;
 
int main()
{
    struct student_detail stu_data = {1, "Raju", 90.5, 71145,
                                       "Anna University"};
    printf(" Id is: %d \n", stu_data.id);
    printf(" Name is: %s \n", stu_data.name);
    printf(" Percentage is: %f \n\n", stu_data.percentage);
 
    printf(" College Id is: %d \n",
                    stu_data.clg_data.college_id);
    printf(" College Name is: %s \n",
                    stu_data.clg_data.college_name);
    return 0;
}
OUTPUT:

Id is: 1
Name is: Raju
Percentage is: 90.500000
 
College Id is: 71145
College Name is: Anna University
C – Union
C Union is also like structure, i.e. collection of different data types which are grouped
together. Each element in a union is called member.

 Union and structure in C  are same in concepts, except allocating memory for their
members.
 Structure allocates storage space for all its members separately.
 Whereas, Union allocates one common storage space for all its members
 We can access only one member of union at a time. We can’t access all member
values at the same time in union. But, structure can access all member values at the
same time. This is because, Union allocates one common storage space for all its
members. Where as Structure allocates storage space for all its members separately.
 Many union variables can be created in a program and memory will be allocated for
each union variable separately.
 Below table will help you how to form a C union, declare a union, initializing and
accessing the members of the union.

Using normal variable Using pointer variable

Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };

Example: Example:
union student union student
{ {
int  mark; int  mark;
char name[10]; char name[10];
float average; float average;
}; };

Declaring union using normal Declaring union using


variable: pointer variable:
union student report; union student *report, rep;

Initializing union using pointer


Initializing union using normal variable:
variable: union student rep = {100, “Mani”, 99.5};
union student report = {100, “Mani”, 99.5}; report = &rep;

Accessing union members using Accessing union members using


normal variable: pointer variable:
report.mark; report  -> mark;
report.name; report -> name;
report.average; report -> average;
EXAMPLE PROGRAM FOR C UNION:

#include <stdio.h>
#include <string.h>
 
union student
{
            char name[20];
            char subject[20];
            float percentage;
};
 
int main()
{
    union student record1;
    union student record2;
 
    // assigning values to record1 union variable
       strcpy(record1.name, "Raju");
       strcpy(record1.subject, "Maths");
       record1.percentage = 86.50;
 
       printf("Union record1 values example\n");
       printf(" Name       : %s \n", record1.name);
       printf(" Subject    : %s \n", record1.subject);
       printf(" Percentage : %f \n\n", record1.percentage);
 
    // assigning values to record2 union variable
       printf("Union record2 values example\n");
       strcpy(record2.name, "Mani");
       printf(" Name       : %s \n", record2.name);
 
       strcpy(record2.subject, "Physics");
       printf(" Subject    : %s \n", record2.subject);
 
       record2.percentage = 99.50;
       printf(" Percentage : %f \n", record2.percentage);
       return 0;
}
OUTPUT:

Union record1 values example


Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
EXPLANATION FOR ABOVE C UNION PROGRAM:
There are 2 union variables declared in this program to understand the difference in
accessing values of union members.

Record1 union variable:


 “Raju” is assigned to union member “record1.name” . The memory location name is
“record1.name” and the value stored in this location is “Raju”.
 Then, “Maths” is assigned to union member “record1.subject”. Now, memory location
name is changed to “record1.subject” with the value “Maths” (Union can hold only one
member at a time).
 Then, “86.50” is assigned to union member “record1.percentage”. Now, memory
location name is changed to “record1.percentage” with value “86.50”.
 Like this, name and value of union member is replaced every time on the common
storage space.
 So, we can always access only one union member for which value is assigned at last.
We can’t access other member values.
 So, only “record1.percentage” value is displayed in output. “record1.name” and
“record1.percentage” are empty.
Record2 union variable:
 If we want to access all member values using union, we have to access the member
before assigning values to other members as shown in record2 union variable in this
program.
 Each union members are accessed in record2 example immediately after assigning
values to them.
 If we don’t access them before assigning values to other member, member name and
value will be over written by other member as all members are using same memory.
 We can’t access all members in union at same time but structure can do that.

DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:


C Structure C Union

Structure allocates storage Union allocates one common storage space for all its
space for all its members members.
separately. Union finds that which of its member needs high storage
space over other members and allocates that much space

Structure occupies higher


memory space. Union occupies lower memory space over structure.

We can access all members


of structure at a time. We can access only one member of union at a time.

Structure example: Union example:


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

For above structure, memory


allocation will be like below.
int mark – 2B
char name[6] – 6B For above union, only 8 bytes of memory will be allocated
double average – 8B  since double data type will occupy maximum space of
Total memory allocation = memory over other data types. 
2+6+8 = 16 Bytes Total memory allocation = 8 Bytes

C – Typedef
 Typedef is a keyword that is used to give a new symbolic name for the existing name
in a C program. This is same like defining alias for the commands.
 Consider the below structure.
struct student
{
         int mark [2];
         char name [10];
         float average;
}

 Variable for the above structure can be declared in two ways.


1st way  :
struct student record;       /* for normal variable */
struct student *record;     /* for pointer variable */
2nd way :
typedef struct student status;

 When we use “typedef” keyword before struct <tag_name> like above, after that we
can simply use type definition “status” in the C program to declare structure variable.
 Now, structure variable declaration will be, “status record”.
 This is equal to “struct student record”. Type definition for “struct student” is
status. i.e. status = “struct student”

AN ALTERNATIVE WAY FOR STRUCTURE DECLARATION USING TYPEDEF IN C:


typedef struct student
{
         int mark [2];
         char name [10];
         float average;
} status;

 To declare structure variable, we can use the below statements.


status record1;                 /* record 1 is structure variable */
status record2;                 /* record 2 is structure variable */

EXAMPLE PROGRAM FOR C TYPEDEF:

// Structure using typedef:


 
#include <stdio.h>
#include <string.h>
 
typedef struct student
{
  int id;
  char name[20];
  float percentage;
} status;
 
int main()
{
  status record;
  record.id=1;
  strcpy(record.name, "Raju");
  record.percentage = 86.5;
  printf(" Id is: %d \n", record.id);
  printf(" Name is: %s \n", record.name);
  printf(" Percentage is: %f \n", record.percentage);
  return 0;
}
OUTPUT:

Id is: 1
Name is: Raju
Percentage is: 86.500000
 Typedef can be used to simplify the real commands as per our need.
 For example, consider below statement.
typedef long long int LLI;
 In above statement, LLI is the type definition for the real C command “long long int”.
We can use type definition LLI instead of using full command “long long int” in a C
program once it is defined.

You might also like