Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Unit V

Pointers
12 Hours
12 Marks

Industry/ Employer expected outcome of this course:


- Develop C programs that address issues with processing strings, mathematic operations
and data structures.

Course Outcome addressed by Unit:


- Write C program using Pointers.

Theory Learning Outcomes:


5.1. Declare and Define Pointer Variable.
5.2. Write C program to print the address and values of pointer variables.
5.3. Write C program to perform arithmetic operations using pointers.
5.4. Write C Program to perform operations on Arrays using Pointers.
5.5. Explain string related operations using pointer.
5.6. Access individual variable of structure using pointer.

Topics and Subtopics:


5.1. Introduction to Pointers : Definition, use of pointers, „*‟ and „&‟ operators, declaring,
initializing, accessing pointers
5.2. Pointer arithmetic
5.3. Pointer to array
5.4. Pointer and Text string
5.5. Function handling using pointers
5.6. Pointers to Structure

Suggested specification table:


Distribution of Theory Marks
Remember Level Understand Level Apply and Above Level Total Marks
02 02 08 12
This specification table provides general guidelines to assist students for their learning
and to teachers to teach and assess students with respect to attainment of Learning Outcomes
(LOs). The actual distribution of marks at different taxonomy levels (R, U and A) in the
question paper may vary from above table.

5.1 What is pointer?


Pointer is a derived data type in C, which is derived from one of the primary data type.
Exact definition of pointer is discussed later.

1 of 18
Normal (or ordinary) variables store values in them. But pointers contain memory
addresses as their values. Pointer is a special variable which holds address of a memory location.
With the help of pointers, memory can be accessed easily. Pointer helps a lot in dynamic
memory allocation.
Following are the benefits of pointers,
- Pointers support dynamic memory management.
- Pointers reduce length and complexity of programs.
- They increase speed of execution. So execution time is reduced.
- Pointer arrays to character strings result in saving of memory space.
- Pointers can be used to return multiple values from a function.
- Pointers also permit references to other functions.
- Pointers are closely associated with arrays. So arrays can be efficiently handled using
pointers.
- Pointers can efficiently handle dynamic data structures like linked lists.

5.1.1 Concept of memory


Primary memory of computer is sequential collection of memory cells. Each cell is
capable of storing one byte of data. Each such cell has an address associated with it. Addresses
start from 0 and the last address depends on size of memory (e.g. for 1MB of memory, address of
last location is 1048575).

Highest Address -
-
-
11
10
9
8
7
6
5
4
3
2
1
0
Figure 5.1: Memory Organization
Whenever a variable is declared, memory space is allocated to it depending on its data
type. One example is shown below.
float a=27.6;
For variable „a‟, 4 bytes of memory is allocated and 27.6 is stored in the memory cells
allocated to it. Address of first location where a variable gets allocation, is the address of the
variable. So address of variable „a‟ is 2763 as per memory allocation shown in figure 5.2. This is
assumption. Actual memory allocation is taken care by memory management system of
operating system. So it may vary.

2 of 18
Highest Address -
-
-
2771
2770
2769
2768
2767
2766
2765
2764
2763
27.6 a
2762
2761
-
-
-
0

Figure 5.2: Memory Allocation for variable „a‟

5.1.2 Accessing address of a variable


As memory allocation is done by operating system, address of a variable is system
dependent. Address of same variable may change at each instance of execution.
We can determine the address of a variable by using „address of ‟ operator (& operator).
This operator can be used only with variables or individual array elements. It cannot be used
with constant values, expressions or array-names.
Some examples are shown below.
Example 1:
int a;
printf(“Address of variable a is %d”,&a);
/* Displays address of variable a in decimal */
Example 2:
float b;
printf(“Address of variable b is %x”,&b);
/* Displays address of a variable b in hexadecimal */
Example 3:
int x[10];
printf(“Address of element a[2] is %d”,&a[2]);
/* Displays address of array element a[2] */

Address of operator cannot be used in following ways.


int a=10,b=24;
printf(“%d”,&(a+b));
float r[5]={8,6,45,2,10};
printf(“%d”,&r);

3 of 18
5.1.3 Declaration of pointer variable
Before studying declaration of a pointer variable, let us discuss definition of a pointer.

Definition of Pointer:
Pointer is a special variable which is used for holding address of memory location
where value of a specific data type is stored.

As discussed before, memory requirements are different for storing values of different
data types. So, only holding the address is not sufficient. Program should be able to know that
data is stored in how many bytes from the starting location. For this purpose, specifying data
type in declaring pointer variable is must.
Syntax of declaring a pointer variable is given below.
data-type *pointer-name;
The asterisk is used for telling compiler that this is declaration of a pointer variable. Here
pointer-name is a special variable which can contain address of memory location where value of
specified data-type is stored.
Some examples are discussed below.
int *ip; ip is a pointer variable that can contain address of memory location where
integer value is stored. (i.e. ip is a int pointer)
float *fp; fp is a pointer variable that can contain address of memory location where
float value is stored. (i.e. fp is a float pointer)
double *dp; dp is a pointer variable that can contain address of memory location where
double value is stored. (i.e. dp is a double pointer)
char *cp; cp is a pointer variable that can contain address of memory location where
char value is stored. (i.e. cp is a char pointer)
Like any other variable, when a pointer variable is declared memory space (2 bytes) is
allocated to it and it contains a random value (i.e. newly declared pointer variable will point to
any memory location randomly).

5.1.4 Initialization of pointer variable


As discussed above, uninitialized pointer points to any random memory location.
Obviously, uninitialized pointers point to invalid addresses. So, uninitialized pointers are
harmful. They may generate erroneous results or may crash the instance of execution.
Uninitialized pointers can be thought as unguided missiles.
It is very much important to initialize pointer variables before using them in the program.
Initialization of a pointer variable can be done by using assignment operator. Value which is to
be assigned to a pointer variable must be an address. The best method of initializing pointer
variable is by using address of a variable.
Care should be taken while initializing pointer variable. We should assign address of
variable of the same data type (as specified in declaration of a pointer variable). e.g. We should
not assign address of a float variable to integer pointer.

Some valid examples of pointer initialization are given here.

4 of 18
Valid Example 1:
int a;
int *ptr;
ptr=&a;
Valid Example 2:
float x,*fp;
fp=&x;
Valid Example 3:
/* We can also set initial value of a pointer as NULL (i.e. „\0‟ ) */
int *ip=NULL; /* OR int *ip=‟\0‟ */

Some invalid examples are given below.


Invalid Example 1:
int a;
float *ptr;
ptr=&a;
Invalid Example 2:
int ip;
float *b;
ip=&b;

5.1.5 Accessing value of memory location where pointer is pointing to


We can use indirection operator „*‟ (asterisk) for accessing (reading or writing) value of
memory location to which pointer is pointing to. Indirection operator is also called as
dereferencing operator. Some valid examples are shown below.
Example 1:
int a,*ptr;
ptr=&a;
/* ptr points to memory location where variable a is stored */
*ptr=25; /* Value of memory location addressed by ptr is set to 25 */
Example 2:
float x,*fp;
x=37.82;
fp=&x;
printf(“%f”,*fp);
/* It will display value of memory location pointed by fp. i.e. 37.82 */

We may also have chain of pointers up to any depth. i.e. we may have pointer which is
pointing to another pointer and so on and the last pointer is pointing to a memory location where
value of specified data type is stored. This is also called as multiple indirections. Some examples
of chain of pointers are discussed here.

5 of 18
Example 1:
float **p;
float *fp,b;
b=10.42;
fp=&b; /* Address of b gets stored in fp */
p=&fp; /* Address of fp gets stored in p */
/* Here p is pointer to pointer */
/* We can access value of b by using b, *fp or **fp */

Example 2:
int ***r,**q,*p,i=7;
p=&i; /* Address of i gets stored in p */
q=&p; /* Address of p gets stored in q */
r=&q; /* Address of q gets stored in r */
printf(“%d %d %d”,*p,**q,***r);
/* In above printf statement, *p displays contents of memory location pointed by
p. i.e. value of variable i (i.e. 7). **q displays contents of memory location
pointed by pointer whose address is stored in q. ***r displays contents of memory
location pointed by pointer whose address is stored in another pointer pointed by
r. */
/* So, the output of above code is 7 7 7 */

Similar to other variables, pointers can be used in expressions. If ip is a pointer, *ip gives
contents of memory location pointed by ip.
Following are some valid examples by considering ptr and pntr as two pointer variables
of same data types (obviously, these pointers must be properly initialized).
res = *ptr + *pntr; /* addition of values of memory locations pointed by ptr
and pntr gets stored in res */
b = a – *pntr; /* value of subtraction of a and value of memory location
pointed by *pntr gets stored in b */
Care must be taken while using division operator along with pointer. As „/*‟ is treated as
beginning of a comment, space should be given in between „/‟ and „*‟ operators as shown in
following example.
res = *ptr / *pntr;
/* It should not be written as res = *ptr /*pntr */

5.2 Pointer Arithmetic


Some arithmetic operations can be performed on pointers. We can add integers to
pointers or subtract integers from pointers. Similarly pointers can also be incremented (pre or
post) as well as decremented (pre or post). We can also apply unary minus operator to pointer.
But we cannot perform addition, multiplication and division of two pointers. Subtraction of two
pointers is possible if they are referring to same array.

6 of 18
Whenever above arithmetic operations are performed on pointers, scale factor is used
automatically. Scale factor is nothing but number of bytes used for storing value of specific data
type. Some examples are discussed below.
Example 1:
int *ip, a[10], i;
ip=a; /* Address of first element of array a gets stored in ip */
for(i=0;i<10;i++)
{
printf(“ %d”,*ip);
ip++;
/* Here ip will be incremented by 2 if size of int data type is 2 */
/* So, individual array element is displayed in each iteration */
}
Example 2:
int *ip, a[10], i;
ip=&a[9];
/* Address of last element of array a (i.e. a[9]) gets stored in ip */
printf(“ %d”,*ip); /* Displays value of a[9] */
ip = ip – 3; /* 3 (multiplied by scale factor) gets subtracted from ip */
printf(“ %d”, *ip); /* Displays value of a[6] */

Relational operators like <, <=, >, >=, == and != can also be used for comparing two
pointers. This comparison is meaningful in case of arrays and strings only.

5.3 Handling Arrays using Pointers


When an array is declared, sufficient memory (required for storing all the elements of
array) is allocated to it sequentially. Base address of array is nothing but address of first element
of array (i.e. address of element at index 0).
Array is always considered as a constant pointer which points to the first element of
array. If an array is defined as,
int a[10];
and if allocation is done as shown figure 5.3, base address of array a is 2412 (assumed in
this example). At location 2412, a[0] is stored . As, „a‟ becomes a constant pointer, it‟s value is
2412 which is nothing but address of element a[0]. It means, values of a and &a[0] are same (i.e.
2412). As „a‟ contains address (base address of array), it can be assigned to any pointer of integer
type. If ip is an integer pointer, following statement is valid.
ip = a; /* It is equivalent to ip = &a[0] */
Above statement copies base address of array „a‟ in the pointer variable ip. We can then
use pointer ip for traversing through (accessing each element of) the array. This can be done by
incrementing the pointer ip by 1. The equivalence between a and ip is shown below.
ip is equivalent to &a[0] which is 2412

7 of 18
ip+1 is equivalent to &a[1] which is 2414
-
ip+8 is equivalent to &a[8] which is 2428
ip+9 is equivalent to &a[9] which is 2430

Highest Memory Location -


-
2430 a[9]

2428 a[8]

2426 a[7]

2424 a[6]

2422 a[5]

2420 a[4]

2418 a[3]

2416 a[2]

2414 a[1]

2412 a[0]
-
0 Memory Location -
Figure 5.3: Sample Memory Allocation for array a
As pointer is equivalent to array a, we can use it for accessing individual elements of
array. Some examples are shown below.
*ip gives value of a[0]
*(ip+1) gives value of a[1]
*(ip+2) gives value of a[2]
*(ip+3) gives value of a[3]
-
-
*(ip+8) gives value of a[8]
*(ip+9) gives value of a[9]
Pointer accessing method is faster than accessing the elements of array by using index of
array.
As an example, code for storing squares of given list (array) of elements into another
array is given below. Different logics are used for reading array elements and for displaying
squares.

int a[5]; /* for storing input list of values */


int b[5]; /* for storing squares */
int i;
8 of 18
int *pa; /* For pointing to array a */
int *pb; /* For pointing to array b */

pa=a;
pb=b;
printf(“Enter five values:\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,(pa+i));

*(pb+i)=*(pa+i) * (*(pa+i));
/* Here, *(pb+i) represents value of b[i] element and *(pa+i)
represents value of a[i] element */
}

printf(“The square values of entered values are:\n”);


for(i=0;i<5;i++)
{
printf(“%d ”,*pb);
pb++; /* pb gets incremented, so in each iteration it points to next
array element of b*/
}

Sample Output:
Enter five values:
26937
The square values of entered values are:
4 36 81 9 49

5.4 Pointers and Text strings


As already discussed previously, strings are nothing but character arrays. A null character
(„\0‟) is automatically inserted at the end of a string. One example of declaring string is given
below.
char name[15];
Above string variable is capable of storing strings containing maximum 14 characters. In
such a string variable, if we store string like “India”, only 6 bytes (5 + 1 for null) of memory is
used and other 9 bytes are wasted.
Alternatively we may use character pointers for declaring strings. Some examples are
shown below.
Example 1:
char *str=“Hello”;
/* creates character array of size 6 (5+1 for null) and stores its base
address in pointer str */

9 of 18
Example 2:
char *name;
name=“Shubman Gill”;
/* This is an example of run-time assignment */
When we declare stings using pointers, only necessary memory gets allocated. So,
wastage of memory is avoided.

Pointers can be used to access individual characters in a string. Example code is shown
below.

/* code for deciding whether string is palindrome or not */


char str[15];
char *ptr1,*ptr2;

printf(“Enter a string: “);


scanf(“%s”,str);
ptr1=str; /* ptr1 points to first character of str */

ptr2=str;
while(*ptr2!=‟\0‟)
{
ptr2++;
}
ptr2--; /* ptr2 points to last character of str */

while(ptr1<ptr2)
{
if(*ptr1==*ptr2)
{
ptr1++;
ptr2--;
}
else
{
break;
}
}
if(ptr1<ptr2)
{
printf(“%s is palindrome”,str);
}
else
{
printf(“%s is not palindrome”,str)l
}

10 of 18
5.5 Handling functions using Pointers
We can also have pointer to function. In such case, pointer is a special variable which is
used for holding address of memory location where function of a specific prototype is stored.
As discussed before, pointer to integer can hold address of memory location where
integer value is stored. It cannot hold address of float variable. Similarly, a pointer to function
can hold address of only the functions whose prototype is matching with the pointer declaration.

Syntax of declaring a pointer to function is given below.


return-type (*pointer-name)([data-types of arguments]);
The asterisk is used for telling compiler that this is declaration of a pointer. Parentheses
around the pointer-name are compulsory and they indicate that the pointer is pointer to function.
If the parentheses are not used around the pointer-name, it is assumed that the function is
returning a pointer.
Some valid examples of initialization of pointer to function are given below.
Valid Example 1:
int add(int,int);
int (*ptr)(int,int);
ptr = add;
Valid Example 2:
float fun1(int);
float (*fptr)(int);
fptr = fun1;

Some invalid examples are given below.


Invalid Example 1:
int add(int,int);
float (*ptr)();
ptr = add;
Invalid Example 2:
float fun2( );
int (*ptr)( );
ptr = fun2;

Some example programs are shown below.

Example Program 1:

int add(int a, int b)


{
int c;
c = a+b;
return c;

11 of 18
}

main( )
{
int x,y,z;
int (*ptr)(int, int);

ptr = add;

printf(“Enter two numbers: ”);


scanf(“%d%d”,&x,&y);

z = ptr(x,y);

printf(“Addition of %d and %d is %d”, x, y, z);


}

Output:
Enter two numbers: 56 72
Addition of 56 and 72 is 128

Example Program 2:

int add(int a, int b)


{
int c;
c = a+b;
return c;
}

int mul(int a, int b)


{
int c;
c = a*b;
return c;
}

main( )
{
int x,y,z;
int (*ptr)(int, int);

printf(“Enter two numbers: ”);


scanf(“%d%d”,&x,&y);

ptr = add;

12 of 18
z = ptr(x,y);

printf(“Addition of %d and %d is %d”, x, y, z);

ptr = mul;
z = ptr(x,y);

printf(“Multiplication of %d and %d is %d”, x, y, z);

Output:
Enter two numbers: 56 72
Addition of 56 and 72 is 128
Multiplication of 56 and 72 is 4032

506 Pointers to structures


We can also have pointer to structure. In such case, pointer is a special variable which is
used for holding address of memory location where members of a specific structure are
stored.
As discussed before, pointer to integer can hold address of memory location where
integer value is stored. It cannot hold address of float variable. Similarly, a pointer to structure
can hold address of only the variables of the structure matching with the pointer declaration.

Syntax of declaring a pointer to structure is given below.


struct structure-name *pointer-name;
The asterisk is used for telling compiler that this is declaration of a pointer. Here pointer
is pointing to memory location where all the members of structure variable of type structure-
name are stored. We may combine the structure definition and pointer declaration as shown
below.

struct structure-name
{
data-type var1;
--
--
} *pointer-name;

Some valid examples of declaration of pointer to structure are given below.


Valid Example 1:
struct student
{
int roll_no;
char name[15];

13 of 18
};

struct student s1;


struct student *ptr;

ptr=&s1; /* Way how pointer to structure is initialized */


Valid Example 2:
struct employee
{
int emp_id;
char name[20];
}*p;

struct employee e1;

p=&e1; /* Way how pointer to structure is initialized */

For accessing members of structure through a pointer variable, arrow operator (->) is
used. For above examples we may access the members as follows.
ptr->roll_no
ptr->name

p->emp_id
p->name

Some example programs for handling structures using pointers are shown below.

Example Program 1:
main( )
{
struct student
{
int roll_no;
char name[15];
};

struct student s1;


struct student *ptr;

ptr=&s1; /* Way how pointer to structure is initialized */

printf(“Enter roll number of student: ”);


scanf(“%d”,&ptr->roll_no);
printf(“Enter name of student: ”);
scanf(“%s”,&ptr->name);

14 of 18
printf(“Data you entered is as follows:\n”);
printf(“Roll Number of Student: %d\n”,ptr->roll_no);
printf(“Name of Student: %s”,ptr->name);
}

Output:
Enter roll number of student: 34
Enter name of student: Sanjivani
Data you entered is as follows:
Roll Number of Student: 34
Name of Student: Sanjivani

Example Program 2:
main( )
{
int i;

struct employee
{
int emp_no;
char name[15];
}e[3],*p;
/* e1 is array of three employees and p is pointer to structure */

ptr=e1; /* Way how pointer to structure array is initialized */


/* As array is constant pointer, & operator is not used */

printf(“Enter data of three employees: \n”);


for(i=0;i<3;i++)
{
printf(“Enter employee ID of employee: ”);
scanf(“%d”,&p->emp_id);
printf(“Enter name of employee: ”);
scanf(“%s”,&p->name);
}

printf(“Data you entered is as follows:\n”);


for(i=0;i<3;i++)
{
printf(“Emp ID: %d\n”,p->emp_id);
printf(“Name of Employee: %s”,p->name);
}
}

15 of 18
Output:
Enter data of three employees:
Enter employee ID of employee: 5222
Enter name of employee: Ramesh
Enter employee ID of employee: 1612
Enter name of employee: Ayush
Enter employee ID of employee: 1213
Enter name of employee: Anay

Data you entered is as follows:


Emp ID: 5222
Name of Employee: Ramesh
Emp ID: 1612
Name of Employee: Ayush
Emp ID: 1213
Name of Employee: Anay

Sample Questions
1. Define pointer. Write syntax for pointer declaration. [2M]
2. State syntax to declare pointer variable with example. [2M]
3. Give any four advantages of pointers. [2M]
4. What is pointer? Give its declaration. [2M]
5. What is pointer? Give one example of integer and character pointer. [2M]
6. Define pointer variable. What are advantages of pointer? [2M]
7. List advantages of using pointer. [2M]
8. State use of '&' and '*' operators with respect to pointer. [2M]
9. State limitations of pointer. [2M]
10. Write output of following program. [2M]
void main( )
{
int ***r,**q,*p,i=7;
p=&i;
q=&p;
r=&q;
printf(“%d%d%d”,*p,**q,***r);
}
11. What is pointer? How is it declared? How is it used? Explain with suitable example [4M]
12. With suitable example, list different pointer arithmetic operations. [4M]
13. Write a program to find length of string using pointers. [4M]
14. Write a program in C using pointer to determine length of a string. [4M]
15. Write a program to find whether string is palindrome (using pointer). [4M]
16. Define pointer. State and describe pointer operators. [4M]
17. List different pointer arithmetic operations. Give example of each. [4M]

16 of 18
18. Explain pointer arithmetic with example. [4M]
19. Explain how array elements are accessed using pointers. [4M]
20. Write a program in C using pointers to compute the sum of elements stored in an array
abc[ ]. [4M]
21. Explain how pointers are used in call-by-reference method of function. [4M]
22. Write a program to print first ten terms of Fibonacci series using pointers [4M]
23. Write the values of d in following component of program. [4M]
int a=20;
int *b=&a;
int *c=b;
int d=*b+*c;
24. State meaning of following statements with respect to pointer. [4M]
int *ptr,m=8;
*ptr=m;
ptr=&m;
25. Explain meaning of following statements with reference to pointers. [4M]
int *ptr,m=10;
ptr=m;
ptr=&m;
26. Explain when to use pointers in a program and give examples of pointer expressions that
can be used in any application program. [4M]
27. Explain meaning of following statements with reference to pointers. [4M]
int *p,x;
x=10;
*p=x;
p=&x;
28. Explain the concept of pointers arithmetic operators with example. [4M]
29. How pointers are declared and accessed? [4M]
30. Explain the concept of pointer arithmetic. [4M]
31. Explain the concept of pointer to array. Give example. [4M]
32. Explain meaning of following statement with reference to pointers. [4M]
int *a,b;
b=20;
*a=b;
a=&b;
33. Write a program to print reverse of entered string using pointer. [6M]
34. Write a program to print values of variables and their addresses. [6M]
35. Write a program to accept a string as input from user and determine its length. [Don‟t use
built-in library function strlen( )] [4M]
36. Write a program to accept two numbers from user and perform addition, subtraction,
multiplication and division operations using pointer. [6M]
37. Explain how to pass pointer to function with example. [4M]
38. Write a program to swap values of variables a=10 and b=5 using function. [4M]
39. Develop a program to swap two numbers using pointer, add swapped numbers and print
their addition. [6M]
40. Distinguish/Differentiate between call by value and call by reference. [2M/4M]

17 of 18
41. Explain pointer arithmetic with example. [4M]
42. State four arithmetic operations performed on pointer with example. [4M]
43. Write output of following C program. [4M]
#include<stdio.h>
int main( )
{
char *ptr;
char str[ ]=“MAHARASHTRA STATE BOARD OF TECHNICAL
EDUCATION”;
ptr=str;
ptr=ptr+11;
printf(“%s”,++ptr);
return 0;
}

44. Give output of following code. [4M]


#include<stdio.h>
void main( )
{
int *arr[4];
int i=10,m=20,n=30,p=40;
int i;
arr[0]=&i;
arr[1]=&m;
arr[2]=&n;
arr[3]=&p;
for(i=0;i<4;i++)
printf(“\n%d”,*a[i]);
}
45. Write a program to swap (exchange) the values of two integer numbers using pointer.
[4M]
46. Explain with suitable example how functions can be handled using pointers. [4M]
47. Explain with suitable example how structure can be handled using pointers. [4M]
48. Implement a program to demonstrate pointer to function. [6M]

18 of 18

You might also like