Unit IV - Pointers, Structures, and Unions
Unit IV - Pointers, Structures, and Unions
STRUCTURE
4.3 Introduction
4.4 Pointers
4.6 Summary
4.7 Keywords
4.10 References
4.1 INTRODUCTION
Pointers are a powerful concept in C and add to its strength. The pointer enables to
121
4. Optimize memory space usage
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
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
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
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.
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 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;
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 ? ?
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,
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;
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.
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;
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,
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
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);
}
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:
133
x *intptr
2000 2002
x *intptr
2000 2002
x *intptr
2000 2002
The precedence level of difference operator increments or decrement operator is same and
them associatively from right to left.
Since the operator associate from right to left, increment operator will apply to the pointer p.
y=*p
134
iii) int y=++*p equivalent to ++(*p) p=p+1 then *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()
x=&a[5];
Pointer to pointer
Addition of pointer variable stored in some other variable is called pointer to pointer variable.
135
Or
p1
*Under revision
9
6
P 2000
X 1000
22
3000
136
Pointer vs array
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.
Creating a structure
// 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
In the following example we are accessing the members of the student structure.
So, to create a pointer for the student structure we will write the following code.
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;
We use the arrow operator also known as member selection operator -> to access the
members of a structure via pointer variable.
ptrName->member
In the following example we are accessing the firstname member of the student structure via
pointer variable ptr.
Complete code
#include <stdio.h>
int main(void) {
// student structure
struct student {
char id[15];
char firstname[64];
char lastname[64];
float points;
};
139
// student structure pointer variable
ptr = &std;
scanf("%s", ptr->id);
scanf("%s", ptr->firstname);
scanf("%s", ptr->lastname);
scanf("%f", &ptr->points);
140
printf("ID: %s\n", ptr->id);
return 0;
Output:
ID: s01
Points: 8.440000
ID: s01
Points: 8.440000
141
4.3 STRUCTURES AND UNIONS
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
struct struct-type
Where,
………
……….
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
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>
}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
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>
146
}structure_variable={value1,value2,…..valueN};
EXAMPLE
struct employeedet
}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.
};
void main()
147
clrscr();
e2=e1;
printf(“e2.empno=%d \n”,e2.empno);
printf(“e2.name=%s \n”,e2.name);
printf(“e2.salry=%8.2f \n\n”,e2.salary);
e2.name=Nishu
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
e.empno=10;
strcpy (e.name,”Kavi”);
2. Assigining one structure variable to another of the same type. struct emp
e1={12,”Kamal”,4000},e1
e2=e1;
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;
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
char name[15];
}s1;
void main()
printf(“Name is %s”,s1.name);
printf(“Name is %s”,s2.name);
s3=s1;
150
printf(“Name is %s”,s3.name);
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(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.
};
void main()
s[i].roll=i+1;
printf("\nName:");
152
}
struct student
char name[30];
int roll,age,marks[5];
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
Nested structure may also be initialized at the time of declaration like in above example.
{“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
};
struct student
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
155
Passing entire structure to function #include<stdio.h> #include<string.h>
struct student
};
display(s1); display(s2);
display(struct student s)
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 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.
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
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
#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(“Mark 1: %d \n”,ul.mark1);
printf(“Mark 2:%d\n”,ul.mark2);
printf(“Mark 3:%d\n”,ul.mark3);
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
};
union b
}; union b bb;
159
There can also be union inside structure or structure in union.
struct a
int i;
char ch[20];
};
struct b
int i;
char d[10];
};
union z
z1.b1.d[0]=”j “;
printf(“ “);
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
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:
int n , avg,i,*p,sum=0;
calloc()
Similar to malloc only difference is that calloc function use to allocate multiple blocks of
memory .
Example:-
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.
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.
int i,*p;
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.
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.
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.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 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
___________________________________________________________________________
__________________________________________________________________________
165
___________________________________________________________________________
__________________________________________________________________________
A. Descriptive Questions
Short Questions
Long Questions
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.
a. String
b. Array
c. Structure
166
d. Files
Main()
Struct emp
Char name[20];
Int age;
167
Float sal;
};
Printf("%d%d%f",e.age,e.sal);
a. garbage collection
b. error
c. 1 0.000000
d. 0 0.000000
Answer
4.8 REFERENCES
References Book
168