You are on page 1of 21

Structures (Unit – VI)

Structure :

A structure is a collection of logically related elements, possibly of different


types, stored in a contiguous memory location sharing a common name. Each
element in a structure is called a field or member.

Structure declaration:

Structures must be declared before they are used. The general format for
declaring a structure is

Where,

 struct is the keyword which tells the compiler that a structure is being
defined.
 tag_name is the name of the structure.
 member1, member2 … are called members of the structure which
may be variables, arrays, pointers or even other structures. The
members are declared within curly braces.
 The closing brace must end with the semicolon.

Example:

Note:

1. The members of the structure do not occupy any memory until they are
associated with the structure variables.

C Programming Notes Page 1


Structures (Unit – VI)

2. All member names with in a particular structure must be different. However,


member names may be same as those of the variables declared outside the
structure.

Declaring structure variables:

Structure variables may be declared in the following ways

Method 1:

The variables of the structure may be declared separately by using the structure
tag as follows

For ex, consider the structure

Now the variables of student structure type can be declared as

struct student s1;

Method 2:

The structure variables can be specified after the closing brace when the
structure is declared.

For ex, consider the following declaration

C Programming Notes Page 2


Structures (Unit – VI)

Where var1,var2,......varn are variables of type structure

Ex:

Here s1 is a variable of student structure type.

Note:

If other variables of the structure are not required, the tag_name can be omitted
as follows.

Where s1,s2,s3 are variables of structure type.

C Programming Notes Page 3


Structures (Unit – VI)

Accessing Structure members:

C provides a dot(.) operator to access the members of a structure


independently. The dot operator is used to link a structure variable and its
member. The syntax for accessing members of a structure variable is

structurevariablename.membername;

for example, consider the following structure

Now each member of the structure variable s1 can be accessed using the dot(.)
operator as follows

s1.rno; /* the statement will access s1’s rno*/

s1.name; /* the statement will access s1’s name*/

s1.avg; /* the statement will access s1’s avg*/

structure Initialization:

Structure variables can be initialized at the time of their declaration. For


example, consider the following structure declaration

C Programming Notes Page 4


Structures (Unit – VI)

A variable of the structure student can be initialized during declaration is as


follows.

struct student s1= { 1,”pavan”, 75.00};

The initial values for the components of the structure are placed in curly braces
and separated by commas. The members of the variable s1 i.e., rno, name, avg
are initialized to 1, “pavan” and 75.00 respectively.

Arrays and structures:

We can declare an array of structures, where each element of the array


represents a structure variable.

Suppose we want to store 20 students’ details. Now we can declare an array of


struct student of size 20 as follows.

struct student x[20];

Here x is an array of student structure type and the array elements


x[0], x[1], x[2] ,.........x[19] can store an individual student’s details.

Arrays with in structures:

It is possible to have an array within the structure i.e., an array as structure


member. For example, consider the structure

struct student

int rno;

char name[80];

int marks[6];

int sum;

float per;

C Programming Notes Page 5


Structures (Unit – VI)

Here we used an array of char type( string) as a member of the structure to


store name of the student and an array of int type as a member of the
structure to store the marks in 6 subjects of the student.

Example program:

/*program to illustrate structures and arrays*/

#include <stdio.h>

struct student

int rollno;

char name[50];

int marks[6];

int sum;

float per;

};

int main()

int i,j,n;

struct student x[100];

clrscr();

printf("Enter total no. of students:\n");

scanf("%d",&n);

printf("Enter information of students:\n");

for(i=0; i<n; i++)

printf("enter details of %d student\n",i+1);

scanf("%d%s",&x[i].rollno,x[i].name);
C Programming Notes Page 6
Structures (Unit – VI)

printf("enter marks of 6 subjects of student %s\n",x[i].name);

for(j=0;j<6;j++)

scanf("%d",&x[i].marks[j]);

for(i=0; i<n; i++)

x[i].sum=0;

for(j=0;j<6;j++)

x[i].sum= x[i].sum+x[i].marks[j];

x[i].per=(float)(x[i].sum/6);

printf("rollno \t\t name \t\t\t per \n");

for(i=0;i<n;i++)

printf("%d\t\t%s\t\t\t%f\n",x[i].rollno,x[i].name,x[i].per);

structures with in structure (nested structures):

In C, it is possible that structures of one type are made the members of another
structure. When a structure contains another structure, it is called nested
structure.

In case of nested structures, the members of the embedded structure can be


accessed by using the following format

Externalstructurevariable . Internalsturucturevariable . membername;

For example, suppose that we have two structures named student and date. To
make date nested to student, we have to define date structure before and outside
student structure and create an member of date structure inside student structure.

C Programming Notes Page 7


Structures (Unit – VI)

The structures date and student are declared as follows

Here the structure student contains the variable of structure date. A variable of
struct student type thus can store rno, name, avg and date of admission(doa) of a
student. Now consider the following statement

struct student x;

Here x can represent details of a student with x.rno, x.name, x.avg and x.doa
respectively. Since x.doa becomes variable of struct date type x.doa.day,
x.doa.month and x.doa.year represent day, month and year part of doa.

C Programming Notes Page 8


Structures (Unit – VI)

Pointers and structures:

A pointer can also store the address of structure variables also.

The syntax for defining pointer to structures is

structurename *ptr1,*ptr2,........., *ptrn;

where ptr1, ptr2, ......, ptrn etc. are pointers to structure variable

The syntax for accessing members of a structure using structure pointer is

structurepointervariable → membername;

Where structurepointervariable is a pointer to a structure variable.

The arrow operator( → ) is used to link a pointer with a member of the


structure.

Ex: consider the following declarations

struct student x, *xp;

here x is a variable of type student structure type and xp is a pointer to the


student structure type. Now the statement

xp = &x;

will assign the address of the variable x to xp. the members of x can be
accessed using xp as

C Programming Notes Page 9


Structures (Unit – VI)

/*program illustrating pointers to structures*/

#include <stdio.h>

struct student

int rollno;

char name[80];

float per;

};

main()

struct student s1 = {1, "pavan", 90.5};

struct student *ptr;

ptr = &s1;

printf("Records of STUDENT: \n");

printf(" rollno is: %d \n", ptr->rollno);

printf(" Name is: %s \n", ptr->name);

printf(" Percentage is: %f \n\n", ptr->per);

Structures containing pointers:

Structure may contain the Pointer variable as member. Pointers are used
to store the address of memory location. They can be de-
referenced by ‘*’ operator.

For example, consider the following structure

struct sample

int *ptr;
C Programming Notes Page 10
Structures (Unit – VI)

char *name;

}s1;

Here s1 is structure variable which is used to access the “structure members”.


suppose num is any integer variable but it’s address is stored in the Structure
member ptr (Pointer to Integer) and Similarly Starting address of the String
“Pavan” is stored in structure variable name(Pointer to Character array) by
using the statements

s1.ptr = &num;

s1.name = “pavan”;

Whenever we need to print the content of variable num , we are dereferancing


the pointer variable num as follows

printf(“ content of num: %d”, *s1.ptr);

printf(“name : %s”,s1.name);

Self Referential structures:

A structure containing a pointer to the same structure type is referred to as


self referential structure. It is useful for implementing data structures such as
linked lists, trees etc. the self referential pointer in the structure points to the
next node of a list.

For example, consider the structure


struct node
{
int data;
struct node *next;
};
The first member is an integer and the second is a pointer to the next node as
shown below.

C Programming Notes Page 11


Structures (Unit – VI)

Structures and Functions

Like an ordinary variable, a structure variable can also be passed to a function.


We may either pass individual structure elements or the entire structure
variables at one go. Let us examine both the approaches one by one using
suitable programs.

/* Passing individual structure elements */

output

Let us C YPK 101

Here in the declaration of the structure, name and author have been declared as
arrays. Therefore, when we call the function display( ) using, display ( b1.name,
b1.author, b1.callno ) ;

we are passing the base addresses of the arrays name and author, but the value
stored in callno. Thus, this is a mixed call—a call by reference as well as a call
by value.

C Programming Notes Page 12


Structures (Unit – VI)

It can be immediately realized that to pass individual elements would


become more tedious as the number of structure elements go on increasing. A
better way would be to pass the entire structure variable at a time. This method
is shown in the following program.

output...

Let us C YPK 101

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.

C Programming Notes Page 13


Structures (Unit – VI)

output...

Let us C YPK 101

Again note that to access the structure elements using pointer to a


structure we have to use the ‘->’ operator.

union:

A union is a special data type available in C that allows to store different


data types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given
time. Unions provide an efficient way of using the same memory location for
multiple-purpose.

The general form of declaring a union is

union unionname
{
datatype member-1;
datatype member-2;
………………….
………………….
datatype member-n;
};
union is a keyword and unionname is any valid identifier.
member-1,member-2, ………….,member-n are the members of the
union.
In case of a union, only one memory location which is large
enough to store largest data type member of the union gets
allocated. This single location can store values of different type
one at a time. But it can be referred by any one individual
member at any point of time.

The syntax for declaring a variable of union type is

union unionname var1,var2,……varn;

C Programming Notes Page 14


Structures (Unit – VI)

ex: consider the following declarations

union number

int i;

float f;

char c;

};

union number n1;

here n1 is a variable of type number union type. As a result, only one memory
location gets allocated and the size of the memory location is four bytes which
is equal to the size of the largest sized data type i.e., float in the memberlist.

/*program to illustrate unions*/

#include <stdio.h>

#include <string.h>

union number

int i;

float f;

char c;

};

main( )

union number n1;

n1.i = 10;

printf( "n1.i : %d\n", n1.i);

n1.f = 220.5;
C Programming Notes Page 15
Structures (Unit – VI)

printf( "n1.f : %f\n", n1.f);

n1.c = ‘p’;

printf( "n1.c: %c\n", n1.c);

Output:

n1.i : 10

n1.f :220.500000

n1.c:p

C Programming Notes Page 16


Structures (Unit – VI)

Differences between Structures and Unions

Structure Union
1.The keyword struct is used to define 1. The keyword union is used to define a
a structure union.
2. In union, the total memory space
allocated is equal to the member with
2. In structure each member get largest size. All other members share the
separate space in memory. Take same memory space. This is the
below example. biggest difference between structure and
union.
struct student
union student
{
{
int rollno;
int rollno;
char gender;
char gender;
float marks;
float marks;
}s1;
}s1;
The total memory required to store a
structure variable is equal to the sum In above example variable marks is of
of size of all the members. In above float type and have largest size (4 bytes).
case 7 bytes (2+1+4) will be required So the total memory required to store
to store structure variable s1. union variable s1 is 4 bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned unique storage area of individual members of union.
location.
4 Altering the value of a member will 4. Altering the value of any of the
not affect other members of the member will alter other member values.
structure.
5. Individual member can be accessed 5. Only one member can be accessed at a
at a time time.
6. Several members of a structure can 6. Only the first member of a union can
initialize at once. be initialized.
Bit fields

C Programming Notes Page 17


Structures (Unit – VI)

Integer fields occupy 16 bits to store data. There are some occasions
where data items require much less than 16 bits space. C Language permits us
to use small bit fields to hold data items and thereby to pack several data items
in a word of memory. A bit field is a set of adjacent bits whose size can be from
1 to 16 bits in length. A word can therefore be divided into a number of bit
fields. The name and size of bit fields are defined using a structure.

Bit Field Declaration

The declaration of a bit-field has the following form inside a structure −

struct {

type [member_name] : width ;

};

The following table describes the variable elements of a bit field −

Elements Description

type An integer type that determines how a bit-field's value is


interpreted. The type may be int, signed int, or unsigned int.

member_name The name of the bit-field.

width The number of bits in the bit-field. The width must be less than
or equal to the bit width of the specified type. The width is
decided by the range of values to be stored. The largest value
that can be stored is 2n-1, where n is width.

The variables defined with a predefined width are called bit fields. A bit
field can hold more than a single bit; for example, if you need a variable to store
a value from 0 to 7, then you can define a bit field with a width of 3 bits as
follows −

struct {

unsigned int age : 3;

} Age;

C Programming Notes Page 18


Structures (Unit – VI)

The above structure definition instructs the C compiler that the age
variable is going to use only 3 bits to store the value. If you try to use more than
3 bits, then it will not allow you to do so.

Several points to observe while using bit fields:

 The first field always starts with the first bit of the word.

 There can be unnamed fields declared with size. Example:

Unsigned : bit-length

 There can be unused bits in a word.

 We cannot take the address of a bit field variable. This means we cannot
use scanf to read values into bit fields. We can neither use pointer to
access the bit fields.

 Bit fields cannot be arrayed.

 Bit fields should be assigned values that are within the range of their size.
If we try to assign larger values, behaviour would be unpredicted.

Suppose your C program contains a number of TRUE/FALSE variables


grouped in a structure called status, as follows −

struct {

unsigned int widthValidated;

unsigned int heightValidated;

} status;

This structure requires 8 bytes of memory space but in actual, we are


going to store either 0 or 1 in each of the variables. The C programming
language offers a better way to utilize the memory space in such situations.

If you are using such variables inside a structure then you can define the
width of a variable which tells the C compiler that you are going to use only
those number of bytes. For example, the above structure can be re-written as
follows −

struct {

C Programming Notes Page 19


Structures (Unit – VI)

unsigned int widthValidated : 1;

unsigned int heightValidated : 1;

} status;

The above structure requires 4 bytes of memory space for status variable,
but only 2 bits will be used to store the values.

If you will use up to 32 variables each one with a width of 1 bit, then also
the status structure will use 4 bytes. However as soon as you have 33 variables,
it will allocate the next slot of the memory and it will start using 8 bytes. Let us
check the following example to understand the concept −

#include <stdio.h>

#include <string.h>

/* define simple structure */

struct {

unsigned int widthValidated;

unsigned int heightValidated;

} status1;

/* define a structure with bit fields */

struct {

unsigned int widthValidated : 1;

unsigned int heightValidated : 1;

} status2;

int main( ) {

printf( "Memory size occupied by status1 : %d\n", sizeof(status1));

printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

return 0;

C Programming Notes Page 20


Structures (Unit – VI)

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

Memory size occupied by status1 : 8

Memory size occupied by status2 : 4

Example Program

#include <stdio.h>

#include <string.h>

struct {

unsigned int age : 3;

} Age;

int main( ) {

Age.age = 4;

printf( "Sizeof( Age ) : %d\n", sizeof(Age) );

printf( "Age.age : %d\n", Age.age );

Age.age = 7;

printf( "Age.age : %d\n", Age.age );

Age.age = 8;

printf( "Age.age : %d\n", Age.age );

return 0;

When the above code is compiled it will compile with a warning and when
executed, it produces the following result −

Sizeof( Age ) : 4

Age.age : 4

Age.age : 7

Age.age : 0
C Programming Notes Page 21

You might also like