0% found this document useful (0 votes)
21 views48 pages

Unit IV - Pointers, Structures, and Unions

This document covers the concepts of pointers, structures, and unions in C programming. It explains the definition, initialization, and operations of pointers, as well as how to access variables through pointers and the importance of memory addressing. The unit also includes learning objectives, examples, and exercises to reinforce understanding of these concepts.

Uploaded by

stallionnexus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views48 pages

Unit IV - Pointers, Structures, and Unions

This document covers the concepts of pointers, structures, and unions in C programming. It explains the definition, initialization, and operations of pointers, as well as how to access variables through pointers and the importance of memory addressing. The unit also includes learning objectives, examples, and exercises to reinforce understanding of these concepts.

Uploaded by

stallionnexus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

UNIT - 4 POINTERS, STRUCTURES, AND UNIONS

STRUCTURE

4.2 Learning Objectives

4.3 Introduction

4.4 Pointers

4.4.1 Operations On Pointers

4.4.2 Pointers & Structures

4.5 Structures And Unions

4.6 Summary

4.7 Keywords

4.8 Learning Activity

4.9 Unit End Questions

4.10 References

4.0 LEARNING OBJECTIVES

After studying this unit, you will be able to:

 Discuss for Pointers Definition and Initialization of Pointer Variables


 Understanding Accessing Variable through its Pointers
 Define Declaring Pointer Variables
 Discuss Different example Program for Pointers

4.1 INTRODUCTION

Pointers are a powerful concept in C and add to its strength. The pointer enables to

1. Write efficient and concise programs

2. Establish inter-program data communication

3. Dynamically allocate and De-Allocate memory

121
4. Optimize memory space usage

5. Deal with hardware components

6. Pass variable number of arguments to functions

The memory (RAM) of a computer is organized as an array of consecutively memory cells.


Since there usually will be several thousands of memory location in the RAM, the CPU needs
some mechanism to identify and request transfer of data from and to a particular location.
This memory is called Addressing.

Each location in the RAM has been given a unique identification number, called an address
of that memory location. Therefore, it is imperative that, every memory location should have
only one address and one address should correspond to only one memory location. Every
variable and every function have an address and these addresses are distinct for each variable
and function.

The identifiers used for variables and functions enable the programmer to refer memory
locations by name. A variable name is a symbolic reference given to a memory location.
Each variable and character string has an address that describes its location. The compiler
translates these names into address. For example, consider the statement product=var1*var2.

If var1 occupies the address 1000 and var2 occupies the address 1005, and product occupies
1025, the above statement will be interpreted by the compiler as move the contents of the
memory location 1000 and 1005 into the CPU registers, multiply them and move the resultant
product to the memory location 1020.

A pointer is a variable that represents the location (rather than a value) of a data item, such as
variable or an array element.

122
4.2 POINTERS

4.2.1 Operations on pointers

The computer’s memory is a sequential collection of „Storage Cells‟ as shown in


following figure. Each cell, commonly known as a byte, has a number called Address
Associated with it. Typically; the addresses are numbered consecutively, starting from
zero.

The last address depends on the memory size. A computer system having 64K memory
willhave its last address as 65535.

Address

Location0
1 .
.
2 .
: .
.
: :
: :
:
: :
: :
:
:
:
:
:
:
:
1022
1023
1024

We know that variables are to be declared before they are used in a program.
Declaration of a variable conveys two things to the compiler. As a result, the compiler

123
1. Allocates a location in memory. The number of bytes in the location depends on
the datatype of the variable.
2. Establishes a mapping between the address of the location and the name of the
variable.

Whenever we declare a variable, the system allocates some location in the memory, an
appropriate location to hold the value of the variable. Since every byte has a unique
address number, this location will have its own address number. Consider the following
declaration of statement:

int price=250;

This statement tells the system to find a location for the integer variable price and put
the value 250 in the location. Let us consider that the system has chosen the address
location 4000 for price. Representation of variable in the following figure:

Quantity Variable
250

4000 Address

During execution of the program, the system always associates the name price with the
address 5000.We may access to the value 250 by using either the name price or the address
4000.Since memory address are simply numbers, they can be assigned to some variables,
which can be stored in memory, like any other variable. Such variables that hold memory
address are called pointer variables. A pointer variable is, therefore, nothing but a variable
that contains an address, which is a location of another variable in memory.

Since a pointer is a variable, its value is also stored in the memory in another location.
Suppose, we assign the address of price to a variable p. The link between the variables p
and quantity can be visualized as shown in the following figure. The address of p is 4050.

124
variable value address
250
price 4000

p 5000 4050

Since the value of the variable p is the address of the variable price, we may access the
value of price by using the value of p and therefore, the variable p „points‟ to the variable
price. Thus, p gets the name „pointer‟

Pointers are constructing on the three important concepts as shown below:

Pointers Pointers Pointers


Constants Values Variables

Pointers

Figure 4.1 3 Important Pointers


Memory address within a computer is referred to as pointer constants. We cannot change
them; we can only use them to store data values. We cannot save the value of a memory
address directly. We can only obtain the value through the variable stored there using the
address operator (&).The value thus obtained is known as pointer value. The pointer value
may change from one program to another.

Once we have a pointer value, it can be stored into another variable. The variable that
contains a pointer value is called a pointer variable.

125
ACCESSING THE ADDRESS OF A VARIABLE

We declare a variable; the amount of memory needed is assigned for it at a specific


location in memory (its memory address). The address that locates a variable within
memory is what we call a reference to that variable. This reference to a variable can be
obtained by preceding the identifier of a variable with an ampersand sign (&), known as
reference operator, and which can be literally translated as "address of".

EXAMPLE

p = &quantity;

This would assign to ted the address of variable quantity, since when preceding the name
of the variable quantity with the reference operator (&) we are no longer talking about the
content of the variable itself, but about its reference (i.e., its address in memory).

From now on we are going to assume that quantity is placed during runtime in the memory
address 2000. This number (2000) is just an arbitrary assumption we are inventing right
now in order to help clarify some concepts in this tutorial, but in reality, we cannot know
before runtime the real value of address of a variable will have in memory.

Consider the following code fragment:

1.quantity = 25;
2.p = quantity;
3.p = &quantity;

EXAMPLE

Write a program to print the address of a variable along with its value.

126
#include<stdi
o.h>
#include<con
io.h> void
main()
{
char
a; int
x;
float
p,q;
a=‟A
‟;
x=12
5;
p=11,q=35.50;
printf(“%c is stored at address %u
\n”,a,&a); printf(“%d is stored at address
%u \n,x,&x”); printf(“%f is stored at
address %u \n”,p,&p);printf(“%f is stored
at address %u”,q,&q);
}

DECLARING POINTER VARIABLES

Declaring pointer variable is quite similar to declaring a normal variable but before
insert astar „*‟ operator before it.

SYNTAX

data-type *pt-name;

where

127
3.The asterisk(*)->represents that the variable pt-name is a pointer
variable2.pt-name->represents memory location
3. pt_name->represents points to a variable of type
data-typeEXAMPLE 1

int *p;

declares the variable p as a pointer variable that points to an integer data type. That the
data type int refers to the data type of the variable being pointer by p and not the value of
the pointer.

EXAMPLE 2

float *x;

Declares x as a pointer to a floating-point variable.

The above pointer variable declaration causes the compiler to allocate memory locations
for the pointer variable p and x. Since the memory locations have not been assigned any
values, these locations may contain some unknown values in them and therefore they point
to unknown locations as shown in the following figure given below:

int *p;

p ? ?

Contains garbage points to unknown location

Can we declare the pointer variable in the following type of the manner?

1. int *p;

2. int *p;

128
3. int *p;

In the second type has become most popular because the following reason,

1. It is convenient to declare multiple declarations in the same manner

EXAMPLE

int *p,x,*q;

2. This type matches with the format used for accessing the target values.

EXAMPLE

int x,*p,y;
x=10;
p=&x;
y=*p;
*p=20;

INITIALIZATION OF POINTER VARIABLES

Like ordinary variables, a pointer variable can also be initialized. Static and external
(global) pointer variables are initialized with NULL by default. When the stat „* operator‟
is applied to a pointer variable to which any address has not been assigned, the pointer
points to an unknown location. So, applying * to such a pointer is dangerous. Therefore,
before a pointer variable is used to access an object, the pointer should be made to point at
a valid object.

Once a pointer variable has been declared we can use the assignment operator to
initialize the variable.

EXAMPLE

129
int price; int
*p;
p=&price;

We can also possibly combine the initialization with the declaration. That is,

int *p=&price;

Pointers are used to be allowed. The only represent here is the variable price must be
declared before the initialization takes place.

Pointer variables always point to the corresponding type of data.

EXAMPLE

float a,bint
x,*p;p=*a;
b=*p;

will result erroneous output because we are trying to assign the address of a float variable
to an integer pointer. When we declare a pointer to be int type, the system assumes that
any address that the pointer will hold will point to an integer variable. Since the
compiler will not detect such errors, care should be taken to avoid wrong pointer
assignments.

int x,*p=&x;

The above statement is perfectly valid. It declares x as an integer variable and p as a


pointer variable and then initializes p to the address of x and the following statement is
also wrong that the target variable x is decal red first.

The statement given below,

130
int *p=&x,x;
is not valid.

It also defines the pointer variable with an initial value NULL or 0(Zero).The
followingstatement given below,

int *p=NULL;int *p=0;

with the exception of NULL and 0,no other constant value can be assigned to a pointer
variable. int *p=5000;

It is also possible to pointers are flexible. We can make the same pointer to point to
different data variables in different statements.

int x,y,z,*p; x y z
…………. p=&x;
…………. p=&y;
………… p=&z; p
………..

It can also possible for different pointers to point the same data variable.

Example

p1 p2 p3
int x;
int *p1=&x;int
*p2=&x; int *p3=&y; x

Accessing Variable through Its Pointers

Pointers are variables that contain address. Suppose v is a variable that represents some

131
particular data item. The compiler will automatically assign memory cells for this data
item. The data item can be accessed if the location (that is the address of the memory cell)
is known. The address of v‟s memory location can be determined by the expression &v,
where & is a unary operator called an address operator. The address v is assigned to
another variable pv as follows: pv=&this new variable is called as pointer to v, since it
points to the location where v is stored.

In above explanation, pv represents v‟s address, not its value. Thus, pv is referred to as a
pointer variable. Pointer variables are declared as follows:

type *variable_name;

For example, a pointer to a character variable is declared as, char *cpt; where the
variable’s name is cpt and the value it holds is a character’s address. The asterisk preceding
the variables name informs the compiler that this variable does not hold the character’s
address and not a character. The * used above is a unary operator and is known as the
indirection or referencing operator. When applied to a pointer, it accesses the object the
pointer points to.

A Variable that contains integer’s address is declared as follows: int *ipt; where iptr is the
name of the pointer variable. Several pointers can also be declared in a single declaration
as: int x, y,*iptr,*jptr; where x and y is regular integers and iptr and jptr are pointers to
integer type of variables. Each data type in C has its own associated pointer type.

A Pointer is to void the generic pointer and can be used to point any type of object.
This implies that a pointer of any type can be assigned to pointers of type void (and vice
versa), if appropriate type casts are used. The void pointer is particularly useful when
various types of pointers are manipulated by a single routine. The void pointer is declared
as follows void *p.

To obtain a variable’s address, the &operator is used. This operator applies only to objects
in the memory such as variables and array elements. It cannot apply to expressions or
constants.

132
EXAMPLE

#include<std
io.h> void
main()
{
int
x,*intptr;
intptr=&x
;
printf(“Enter an
integer”);
scanf(“%d”,intptr);
printf(“\n The value entered is %d \n”,x);
}

Sample program output

Enter an integer:
1234 The value
entered is: 1234

In the above program, two variables, an integer name x and pointer to an integer name int
ptr. The variable int ptr is set to the address of the variable x. The value of the pointer
variable, int ptr is passed to the scanf () function instead of &x, the address of x.

In the above example, if the variable x is at memory location 2000 and intptr which is also
another variable (pointer) has its own memory location. The value assignments and storage
locations in the program samepoint.c would be given below:

After the int x,*intptr;

133
x *intptr
2000 2002

After the line intptr=&x;

x *intptr
2000 2002

After the line of scanf(“%d”,input)

x *intptr
2000 2002

Precedence of dereference (*) Operator and increment operator and decrement


operator

The precedence level of difference operator increments or decrement operator is same and
them associatively from right to left.

Example :- int x=25; int *p=&x;

Let us calculate int y=*p++; Equivalent to *(p++)

Since the operator associate from right to left, increment operator will apply to the pointer p.

i) int y=*p++; equivalent to *(p++) p =p++ or p=p+1


ii) *++p;→*(++p)→p=p+1

y=*p

134
iii) int y=++*p equivalent to ++(*p) p=p+1 then *p

iv) y=(*p)++→equivalent to *p++ y=*p then


P=p+1 ;

Since it is postfix increment the value of p.

Pointer Comparison

Pointer variable can be compared when both variable, object of same data type and it is
useful when both pointers variable points to element of same array.

Moreover, pointer variable is compared with zero which is usually expressed as null, so
several operators are used for comparison like the relational operator.

==,!=,<=,<,>,>=, can be used with pointer. Equal and not equal operators used to compare
two pointers should finding whether they contain same address or not and they will equal
only if are null or contains address of same variable.

Ex:-

void main()

static int arr[]={20,25,15,27,105,96} int *x,*y;

x=&a[5];

y=&(a+5); if(x==y) printf(“same”); else printf(“not”);

Pointer to pointer

Addition of pointer variable stored in some other variable is called pointer to pointer variable.

135
Or

Pointer within another pointer is called pointer to pointer. Syntax:-

Data type **p; int x=22;

int *p=&x; int **p1=&p;

printf(“value of x=%d”,x); printf(“value of x=%d”,*p); printf(“value of x=%d”,*&x);


printf(“value of x=%d”,**p1); printf(“value of p=%u”,&p); printf(“address of p=%u”,p1);
printf(“address of x=%u”,p); printf(“address of p1=%u”,&p1); printf(“value of p=%u”,p);
printf(“value of p=%u”,&x);

p1

*Under revision
9
6

P 2000
X 1000

22

3000

136
Pointer vs array

Example :- void main()

static char arr[]=”Rama”; char*p=”Rama”; printf(“%s%s”, arr, p);

In the above example, at the first time printf( ), print the same value array and pointer.

Here array arr, as pointer to character and p act as a pointer to array of character . When
we are trying to increase the value of arr it would give the error because it’s known to
compiler about an array and its base address which is always printed to base address is known
as constant pointer and the base address of array which is not allowed by the compiler.

printf(“size of (p)”,size of (ar)); size of (p) 2/4 bytes

size of(ar) 5 byes

4.2.2 pointers & structures

Creating a structure

Let’s start by creating a structure variable student as shown below.

// student structure

struct student {

char id[15];

char firstname[64];

char lastname[64];

float points;

};

Now we will create a student structure variable std. For this we will write the following code.

137
// student structure variable

struct student std;

Access the members of a structure

We know that to access a member of a structure we use the . operator.

In the following example we are accessing the members of the student structure.

printf("ID: %s\n", std.id);

printf("First Name: %s\n", std.firstname);

printf("Last Name: %s\n", std.lastname);

printf("Points: %f\n", std.points);

Creating pointer for structure

Following is the syntax to create a pointer for a structure.

struct tagName *ptrName;

So, to create a pointer for the student structure we will write the following code.

struct student *ptr;

Assigning structure variable to pointer

We use the following syntax to assign a structure variable address to a pointer.

ptrName = &structVarName;

In the following example we are assigning the address of the structure variable std to the
structure pointer variable ptr. So, ptr is pointing at std.

138
ptr = &std;

Accessing the members of a structure via pointer

We use the arrow operator also known as member selection operator -> to access the
members of a structure via pointer variable.

Following is the syntax for accessing members of a structure via pointer.

ptrName->member

In the following example we are accessing the firstname member of the student structure via
pointer variable ptr.

printf("First Name: %s", ptr->firstname);

Complete code

#include <stdio.h>

int main(void) {

// student structure

struct student {

char id[15];

char firstname[64];

char lastname[64];

float points;

};

// student structure variable

struct student std;

139
// student structure pointer variable

struct student *ptr = NULL;

// assign std to ptr

ptr = &std;

// get student detail from user

printf("Enter ID: ");

scanf("%s", ptr->id);

printf("Enter first name: ");

scanf("%s", ptr->firstname);

printf("Enter last name: ");

scanf("%s", ptr->lastname);

printf("Enter Points: ");

scanf("%f", &ptr->points);

// display result via std variable

printf("\nResult via std\n");

printf("ID: %s\n", std.id);

printf("First Name: %s\n", std.firstname);

printf("Last Name: %s\n", std.lastname);

printf("Points: %f\n", std.points);

// display result via ptr variable

printf("\nResult via ptr\n");

140
printf("ID: %s\n", ptr->id);

printf("First Name: %s\n", ptr->firstname);

printf("Last Name: %s\n", ptr->lastname);

printf("Points: %f\n", ptr->points);

return 0;

Output:

Enter ID: s01

Enter first name: Yusuf

Enter last name: Shakeel

Enter Points: 8.44

Result via std

ID: s01

First Name: Yusuf

Last Name: Shakeel

Points: 8.440000

Result via ptr

ID: s01

First Name: Yusuf

Last Name: Shakeel

Points: 8.440000

141
4.3 STRUCTURES AND UNIONS

A Structure is a derived type usually representing a collection of variables of same or


different data types grouped together under a single name. The variables or data items in a
structure are called as members of a structure. A structure may contain one or more integer
variables, floating-point variables characters variables, arrays, pointers, and even other
structures can also be included as members. Structures help to organize data, particularly in
large programs, because they allow a group of related variables to be treated as a single unit.

There are two fundamental differences between structures and arrays.1.An array demands a
homogeneous data type, i.e., the elements of an array must be of the same data type, whereas
structure is a heterogeneous data type, since it can have any data type as its member.2.The
difference is that elements in an array are referred by their positions, whereas members in a
structure are referred by their unique name.

DECLARING A STRUCTURE

A structure within a C program is defined as follows:

struct struct-type

Where,

member-type1 member-name1; member-type2 member-name2;

………

……….

struct->is a keyword

142
struct type->is a name (tag) that identifies structures of composition member-type1 member
name1.member-type2 member name2…are individual declaration.

The individual members can be ordinary variables, pointers, arrays, or other structures. The
member names within a particular structure must be distinct from one another; thought a
member name can be the same as the name of a variable defined outside the structure.

A storage class cannot be assigned to an individual member, and individual members cannot
be initialized within a structure type declaration. Unlike the declaration of a variable of array,
defining a structure causes no storage to be reserved.

By defining a structure, the programmers derive a new data type composed of a collection of
already known data types and their name. For example, suppose that the information about
10000 business accounts has to be maintained. The information consists of mixed data types,
where for each account the following are required.

EXAMPLE

account number (int)


account type (short)
name (30 char array)
street address (30 char array)
city/state/zip (30 char array)
balance long
last payment (long) date

struct account

int acct_no;

short acct_type;

143
char name[30];

char street[30];

char city_state[30];

long balance;

long last_payment;

};

DEFINING A STRUCTURE

Declaring a structure is just a skeleton it merely describes the template. It does not reserve
any memory space rather than the declaration creates a new data type. To use the structure,
you have to define it. Defining a structure means creating variables to access the members in
the structure. Creating a structure variable allocates sufficient memory space to hold all the
members of the structure. Structures variables can be created during structure declaration or
by explicitly using the structure name.

SYNTAX

struct <structure-name>

data type member1; data type member2; data type member3;

data type member;

}structure variable(s);

EXAMPLE

144
struct employee

int empno;

char empname[15];

float salary;

}emp1

Where the structure employee declares a variable empl of its type. The structure variable(s)
are declared like an ordinary variable is used to access the members of the structure. More
than one structure variable can also be declared by placing a comma in between the
variables.

Once the composition of the structures has been defined, individual structures variables can
be declared as follows: storage class struct struct_type variable 1, variable2… variable;

A variable of the above type id declared like this: struct account. Where the variable name is
customer and the data type is structed account. It is also possible to define a structure and
declare a variable of that at the same time:

SYNTAX

Storage-class struct struct-type

member_type1 memebr_name1;

member_type2 memebr_name2;

member_type3 memebr_name3;

………..

145
member_typen memebr_namen;

variable1, variable2….variable n;

The following figure shows the memory allocation of structure shown in the following figure:

empno 2 bytes

empname 15 bytes

salary 4 bytes
NOTE

The keyword struct is optional when defining the structure using the structure name.

INITIALIZING A STRUCTURE

Similar to initialization of arrays, we can initialize structure variables also. The initializing a
structure variable expressed is expressed as:

SYNTAX

struct <structure_name>

data type member1;

data type member;

146
}structure_variable={value1,value2,…..valueN};

EXAMPLE

struct employeedet

int height; float weight;

}emp1={165,60};

the above initialization initializes 165 to the structure member height and 60 to the structure
member weight. The value to be initialized for the structure members must be enclosed
within a pair of braces.

NOTE

The constants to be initialized to the structure members must be in the same order in which
the members are declared in the structure.

Write a program to initializing a structure using the structure name.

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

int empno; char name[20]; float salary;

};

void main()

struct emp e1,e2; int size;

147
clrscr();

printf(“Enter empno,name and salary \n”); scanf(“%d %sf”,&e1.empno,e1.name,&e1.salary);


size=sizeof(e1);

printf(“\n No. of bytes required for e1=%d \n\n”,size);

e2=e1;

printf(“After assigning e1 to e2 \n\n”);

printf(“e2.empno=%d \n”,e2.empno);

printf(“e2.name=%s \n”,e2.name);

printf(“e2.salry=%8.2f \n\n”,e2.salary);

printf(“Address of 1= %u \n”,&e1); getch();

Sample Program Output

Enter empno, name and salary 123 Nishu 3456

No. of bytes required for e1=26 After assigning e1 to e2 e2.empno=123

e2.name=Nishu

e2.salry=3456.00 Address of e1=65498

e1 and e2 are declared to be variables of struct emp type. Both can accommodate details of
an employee. Details of an employee are accepted into the variable e1.The number of bytes
occupied by a variable of struct emp type is found out with the help of the operator sizeof()
by passing e1 to it. The value returned by sizeof() is then displayed. To illustrate the fact that
structure variables assignment is permissible, e1 is assigned to e2.The contents of e2 are then
displayed. The address of operator & is used with e1 to obtain its address and it is then
displayed.

OPERATIONS ON STRUCUTRES

148
The number of operations which can be performed over structures is limited. Following are
the permissible operations:

1. Accessing the individual members of a structure variable with the help of members
operator (using dot operator)

EXAMPLE

In the case of a variable of type struct emp, struct emp e;

e.empno=10;

10 are assigned to empno number of e.

strcpy (e.name,”Kavi”);

The string “Kavi” is copied to name number of e.

2. Assigining one structure variable to another of the same type. struct emp
e1={12,”Kamal”,4000},e1

e2=e1;

e1 has been assigned to e2.

3. Retrieving the size of a structure variable using sizeof() operator. struct emp e

int e; s=sizeof(e);

4. Retrieving the address of a structure variable using & (address of) operator. struct emp e;

5. Passing and returning a structure variable value to and from a function.

149
6. Checking whether two structure variables of same type are equal using ==.If s1 and s2 are
two variables of the same structure type, s1==s2 returns 1 and if all the members of s1 are
equal to the corresponding members of s2,it returns 0.

7. Checking whether two structure variables of same type and not equal using! =.If s1 and s2
are two variables of the same structure type,s1!=s2 returns 1 and if all the members of s1
are not equal to the corresponding members of s2,it returns 0.

Example

Write a program to perform operation of structure

#include<stdio.h> struct classroom

char name[15];

long int reg_no;

}s1;

void main()

struct classroom s1={sudhakar”,”5690823”);

struct classroom sw=(“ragul”);

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

printf(\n Reg no is %d”,s1.reg_no);

printf(“Name is %s”,s2.name);

printf(\n Reg no is %d”,s2.reg_no);

s3=s1;

150
printf(“Name is %s”,s3.name);

printf(\n Reg no is %d”,s3.reg_no);

Sample program output

Name is kavitha Reg no is 5690823

Name is kamal Reg no is 5690853

Name is martin Reg no is 5690821

The values to be initialized of the members of a structure must be enclosed within a pair of
braces.

Note

The constants to be defined to the members of the structure must be in the same order in
which the members are declared in the structure. The information contained in one structure
variable can also be assigned to another structure variable using a single assignment
statement.

s3=s1

to copy of the values in the structure variable s1 to s3.This type of assignment statements will
be necessary when many members of the structure are to be to declared. The structure
variable can be assigned to another only when they both are of the same structure type.

Size of structure-

151
Size of structure can be found out using sizeof() operator with structure variable name or tag
name with keyword.

sizeof(struct student); or sizeof(s1);

sizeof(s2);

Size of structure is different in different machines. So size of whole structure may not be
equal to sum of size of its members.

Array of structures

When database of any element is used in huge amount, we prefer Array of structures.

Example: suppose we want to maintain data base of 200 students, Array of structures is used.

#include<stdio.h> #include<string.h> struct student

char name[30]; char branch[25]; int roll;

};

void main()

struct student s[200]; int i;

s[i].roll=i+1;

printf("\nEnter information of students:"); for(i=0;i<200;i++)

printf("\nEnter the roll no:%d\n",s[i].roll); printf("\nEnter the name:"); scanf("%s",s[i].name);

printf("\nEnter the branch:"); scanf("%s",s[i].branch); printf("\n");

printf("\nDisplaying information of students:\n\n"); for(i=0;i<200;i++)

printf("\n\nInformation for roll no%d:\n",i+1);

printf("\nName:");

puts(s[i].name); printf("\nBranch:"); puts(s[i].branch);

152
}

In Array of structures each element of array is of structure type as in above example.

Array within structures

struct student

char name[30];

int roll,age,marks[5];

}; struct student s[200];

We can also initialize using same syntax as in array.

Nested structure

When a structure is within another structure, it is called Nested structure. A structure variable
can be a member of another structure and it is represented as

struct student

element 1;

element 2;

………

………

struct student1

member 1;

153
member 2;

}variable 1;

……….

………. element n;

}variable 2;

It is possible to define structure outside & declare its variable inside other structure.

struct date

int date,month;

};

struct student

char nm[20]; int roll; struct date d;

}; struct student s1; struct student s2,s3;

Nested structure may also be initialized at the time of declaration like in above example.

struct student s={“name”,200, {date, month}};

{“ram”,201, {12,11}};

Nesting of structure within itself is not valid. Nesting of structure can be extended to any
level.

struct time

154
int hr,min;

};

struct day

int date,month; struct time t1;

};

struct student

char nm[20]; struct day d;

}stud1, stud2, stud3;

Passing structure elements to function

We can pass each element of the structure through function but passing individual element is
difficult when number of structure element increases. To overcome this, we use to pass the
whole structure through function instead of passing individual element.#include<stdio.h>
#include<string.h> void main()

struct student

char name[30]; char branch[25]; int roll;

}struct student s; printf(“\n enter name=”);

gets(s.name); printf("\nEnter roll:"); scanf("%d",&s.roll); printf("\nEnter branch:");


gets(s.branch); display(name,roll,branch);

display(char name, int roll, char branch)

printf(“\n name=%s,\n roll=%d, \n branch=%s”, s.name, s.roll. s.branch);

155
Passing entire structure to function #include<stdio.h> #include<string.h>

struct student

char name[30]; int age,roll;

};

display(struct student); //passing entire structure void main()

struct student s1={”sona”,16,101 }; struct student s2={”rupa”,17,102 };

display(s1); display(s2);

display(struct student s)

printf(“\n name=%s, \n age=%d ,\n roll=%d”, s.name, s.age, s.roll);

Output: name=sona

roll=16

Union

Unions like structure contain members whose individual data types may differ from one
another. However, the members that compose a union all share the same storage area within
the computer’s memory whereas each member within a structure is assigned its own unique
storage area. Thus, unions are used to observe memory. They are useful for application

156
involving multiple members. Values need not be assigned to all the members at one time.
Like structures union can be declared using the keyword union as follows:

Before instantiating variables of some union type, the data items which are to share a
common name should be grouped together. This is done with the help of union template.

SYNTAX

union tag_name

Where

data-type member1; data-type memebr2;

data-type member n;

union->is a keyword.

tag-name->is any user-defined name, which should be valid C identifier. data-type->is any
valid data type supported by C or user-defined type.

member1,member2…member->are the members of the union The syntax of declaring a


variable of union type is:

union tag_name variable_name;

A memory location gets allocated, the size of which is equal to that of the largest of the
members member1,member2,member3,…..member accessing the members of a union is

157
similar to accessing the members of a structed operator is used to access each individual
member. Dot operator expects union variable to its left and member name to its right.

Example

union item

int m; float p; char c;

code;

union item makes a group of three data items of type int, float and char.

union item t;

A variable t declared to be of type union temp. As a result of this; only one memory location
gets allocated. It can be referred to by any one individual member at any point of time. The
size of the memory location is four bytes, which happens to be the size of the largest sized
data type float in the member list.

Example

Write a program to demonstrate initialization of a union

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

void main()

int roll_no,mark1,mark2,mark3;

}ul;

158
void main()

ul.roll_no=459; ul.mark1=87;

printf(“Roll Number:%d \n”,ul.roll_no);

printf(“Mark 1: %d \n”,ul.mark1);

printf(“Mark 2:%d\n”,ul.mark2);

printf(“Mark 3:%d\n”,ul.mark3);

Sample program output

Roll No:459 Mark 1:87

Mark 2:87

Mark 3:87

Thus, the program, even the uninitialized members (that is mark2 and mark3) take the same
value as the other members.

Nested of Union

When one union is inside another union it is called nested of union. Example:-

union a

int i; int age;

};

union b

char name[10]; union a aa;

}; union b bb;

159
There can also be union inside structure or structure in union.

Example:- void main()

struct a

int i;

char ch[20];

};

struct b

int i;

char d[10];

};

union z

struct a a1; struct b b1;

}; union z z1; z1.b1.j=20; z1.a1.i=10; z1.a1.ch[10]= “ i“;

z1.b1.d[0]=”j “;

printf(“ “);

Dynamic memory Allocation

The process of allocating memory at the time of execution or at the runtime, is called
dynamic memory location.

160
Two types of problem may occur in static memory allocation.

If number of values to be stored is less than the size of memory, there would be wastage of
memory.

If we would want to store more values by increase in size during the execution on assigned
size then it fails.

Allocation and release of memory space can be done with the help of some library function
called dynamic memory allocation function. These library functions are called as dynamic
memory allocation function. These library function prototypes are found in the header file,
“alloc.h” where it has defined.

Function take memory from memory area is called heap and release when not required.

Pointer has important role in the dynamic memory allocation to allocate memory.

malloc():

This function use to allocate memory during run time, its declaration is void*malloc(size);

malloc ()

returns the pointer to the 1st byte and allocate memory, and its return type is void, which can
be type cast such as:

int *p=(datatype*)malloc(size)

If memory location is successful, it returns the address of the memory chunk that was
allocated and it returns null on unsuccessful and from the above declaration a pointer of
type(datatype) and size in byte.

And datatype pointer used to typecast the pointer returned by malloc and this typecasting is
necessary since, malloc() by default returns a pointer to void.

Example int*p=(int*)malloc(10);

So, from the above pointer p, allocated IO contiguous memory space address of 1 st byte and
is stored in the variable.

We can also use, the size of operator to specify the size, such as

*p=(int*)malloc(5*size of int) Here, 5 is the no. of data.

Moreover , it returns null, if no sufficient memory available , we should always check the
malloc return such as, if(p==null)

161
printf(“not sufficient memory”);

Example:

/*calculate the average of mark*/ void main()

int n , avg,i,*p,sum=0;

printf("enter the no. of marks ”); scanf(“%d”,&n);

p=(int *)malloc(n*size(int)); if(p==null)

printf(“not sufficient”); exit();

for(i=0;i<n;i++) scanf(“%d”,(p+i)); for(i=0;i<n;i++) Printf(“%d”,*(p+i)); sum=sum+*p;


avg=sum/n; printf(“avg=%d”,avg);

calloc()

Similar to malloc only difference is that calloc function use to allocate multiple blocks of
memory .

two arguments are there

1st argument specifies number of blocks

2nd argument specifies size of each block.

Example:-

int *p= (int*) calloc(5, 2); int*p=(int *)calloc(5, size of (int));

Another difference between malloc and calloc is by default memory allocated by malloc
contains garbage value, whereas memory allocated by calloc is initialized by zero(but this
initialization) is not reliable.

162
realloc()

The function realloc use to change the size of the memory block and it alter the size of the
memory block without losing the old data, it is called reallocation of memory.

It takes two argument such as; int *ptr=(int *)malloc(size);

int*p=(int *)realloc(ptr, new size);

The new size allocated may be larger or smaller.

If new size is larger than the old size, then old data is not lost and newly allocated bytes are
uninitialized. If old address is not sufficient then starting address contained in pointer may be
changed and this reallocation function moves content of old block into the new block and
data on the old block is not lost.

Example: #include<stdio.h> #include<alloc.h> void main()

int i,*p;

p=(int*)malloc(5*size of (int)); if(p==null)

printf(“space not available”); exit();

printf(“enter 5 integer”); for(i=0;i<5;i++)

scanf(“%d”,(p+i)); int*ptr=(int*)realloc(9*size of (int) ); if(ptr==null)

printf(“not available”); exit();

printf(“enter 4 more integer”); for(i=5;i<9;i++) scanf(“%d”,(p+i)); for(i=0;i<9;i++)

printf(“%d”,*(p+i));

163
free()

Function free() is used to release space allocated dynamically, the memory released by free()
is made available to heap again. It can be used for further purpose.

Syntax for free declaration . void(*ptr)

Or

free(p)

When program is terminated, memory released automatically by the operating system. Even
we don’t free the memory, it doesn’t give error, thus lead to memory leak.

We can’t free the memory, those didn’t allocate.

Difference between Structure And Union

1. Union allocates the memory equal to the maximum memory required by the member of
the union but structure allocates the memory equal to the total memory required by the
members.

2. In union, one block is used by all the member of the union but in case of structure, each
member has their own memory space.

3. Union is best in the environment where memory is less as it shares the memory allocated.
But structure cannot implement in shared memory.

4. As memory is shared, ambiguities are more in union, but less in structure.

Self-referential union cannot be implemented in any data structure, but self-referential


structure can be implemented.

4.4 SUMMARY

 A pointer is a variable, which represents the memory location (not the value) of a data
items, such as a variable or an array element.
 Like all variables a pointer variable should also be declared before they are used.
 The ampersand operator (&) gives the address of a variable.
 The three values that can be used to initialize the pointer are zero, null and address.
 The pointer that has not been initialized is referred to as the dangling pointer.

164
A structure is a derived type usually representing a collection of variables of same or
different data types grouped together under a single name

The keyword struct begins the structure declaration followed by the structure name, the
structure members are enclosed in braces, followed by the semicolon which ends the structure
declaration.

The variable or data items in a structure are called as members of the structure.

Usually, the structure type declaration appears at the top of the source code file, before
any variables or functions are defined.

Structure variables may be initialized with a structure variable of the same type.

A structure that contains another structure as its member is called as nesting of


structures.

A union is another compound data type like a structure that may hold the variables of
different types and sizes, with the compiler keeping track of the size.

4.5 KEYWORDS

 Attributes: Each entity in the world is described by a number of characteristics.


These descriptive characteristics of an entity are called attributes.
 Structure: A structure is a derived type usually representing a collection of variables
of same or different data types grouped together under a single name.
 Tag: A user defined structure name usually referred to as tag.
 Nested Structures: Nested structures are nothing but a structure with another
structure is called nested structures.

4.6 LEARNING ACTIVITY

1. Define a pointer variable

___________________________________________________________________________
__________________________________________________________________________

2. Explain the uses of pointers

165
___________________________________________________________________________
__________________________________________________________________________

4.7 UNIT END QUESTIONS

A. Descriptive Questions

Short Questions

1. What is the meaning of the following declaration: int *px;

2. The indirection operator can be applied to type of operand.

3. State the uses of address operator in pointers.

4. State the uses of indirection operator in pointers.

5. State the need for memory allocation in programs

Long Questions

1. Write a program to find the largest of three number using pointers.

2. Write a program to sort the strings in alphabetical order using pointers.

3. What are the advantages of pointer?

4. Give the significance of & and * operators

5. Differentiate between structure and union.

6. Write a program to create a „list of books‟ details. The details of a book include title,
author, and publishing year, number of pages and price.

7. Explain union with an example, and state the uses of union.

8. Explain the concept of initialization of variables in a union.

B. Multiple Choice Questions

1. Which of the following is a collection of different data types?

a. String

b. Array

c. Structure

166
d. Files

2. Which operator is used to connect structure name to its member name?

a. Dot operator (.)


b. Logical operator (&&)
c. c. Pointer operator (&)
d. Arrow operator (->)

3. Which of the following comment about union is false?

a. A. Union is a structure whose members share same memory area


b. B. The compiler will keep track of what type of information is currently stored
c. C. Only one of the members of union can be assigned a value at particular time
d. D. Size allocated for union is the size of its member needing the maximum storage\

4. Which of the following comment about the usage of structures in true?

a. A. Storage class can be assigned to individual member


b. B. The scope of the member’s name is confined to the particular structure, within
which it is
c. Defined
d. C. Individual members can be initialized within a structure type declaration
e. D. None of these

5. What is the output of following c code?

Main()

Struct emp

Char name[20];

Int age;

167
Float sal;

};

Struct emp e ={"tiger"}

Printf("%d%d%f",e.age,e.sal);

a. garbage collection
b. error
c. 1 0.000000
d. 0 0.000000

Answer

1-c, 2-a, 3-b, 4-b, 5-d

4.8 REFERENCES

References Book

 Turbo C/C++ - The Complete Reference - H.Schidt


 Programming in C - S.Kochan
 Born to code in C - H.Schidt
 The Art of C - H.Schidt
 C Programming - Keringhan and Ritchie - 2nd Ed.
 Programming in ANSI C - Agarwal
 Let us C - Kanitkar
 Programming in ANSI C - Bal Guruswamy

168

You might also like