Session-13
Session Overview
Pointers Introduction
Applications of Pointers
Pointer variables
Pointer operators
Assigning values to Pointers
Pointer Arithmetic
Pointer Comparisons
Pointers as Function Arguments
1
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Introduction
Before looking into Pointers, we must put a keen observation on storing a value
in a variable.
eg. int i=3;
This declaration tells the C compiler to:
a) Reserve space in memory to hold the integer value.
b) Associate the name i with this memory location.
c) Store the value 3 at this location.
We may represent i‘s location in memory by the following memory map.
Computer has selected memory
i location name
location 65524 as a place to store
3 value at location
the value 3. Computer may choose
different memory location some 65524 location number
other time.
2
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Introduction
Pointers are one of the strongest features of C.
A Pointer provides a way to access a variable without referring to the variable
directly.
It provides a symbolic way of using addresses.
A Pointer is a variable, which contains the address of a memory location of
another variable.
If one variable contains the address of another variable, then the first variable
is said to point to the second.
A pointer provides an indirect way of accessing the value of a data item.
3
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Introduction with example
Consider two variables var and ptr has a value of 500 and is stored in the
memory location 1000.
If ptr is declared as a Pointer to the variable var, the representation will be like
Here ptr contains the value 1000, which is Memory Value Variable
Location Stored name
nothing but the address of the variable var. 1000 500 var
1001
1002
ptr var
…..
1000 500 Values
1108 1000 Addresses
1108 1000 ptr
4
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Applications of Pointers
Pointers can point to variables of other fundamental data type variables like
int, char, or double or data arguments like arrays and structures.
Pointers are used in the situations when passing actual values is difficult or not
desired.
Few of the situations where Pointers can be used are
To return more than one value from a function.
To pass Arrays and Strings more conveniently from one function to another.
To allocate memory and access it (Dynamic memory allocation)
To create complex data structures, such as linked lists, where one data structures
must contain references to other data structures.
5
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Variables
A Pointer declaration consists of a base type and a variable name.
The general syntax for declaring a pointer variable is type * name;
where type is any valid data type, and name is the name of the pointer
variable.
The declaration tells the compiler that name is used to store the address of a
value of type type.
Remember that type does not imply that name is of that data type type.
In the declaration statement, * indicates that a pointer variable is being
declared.
6
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Variables
As discussed, ptr is a pointer, which holds the address of an int type variable
var, if will be declared as :
int * ptr;
Remember, ptr is not of type int but is a pointer to a variable of type int.
Multiple pointers require using a * before each variable definition.
int * myptr1, *myptr2;
7
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer variable contd.
Normal Variables Pointer Variables
Contain a specific value Contain memory addresses as their values
Direct reference Indirect Reference (Pointers contain address of a variable
that has a specific value)
No Symbol needed to declare * is used to declare a Pointer Variable
eg. A character (char) is usually eg. A pointer to a character (char*) is usually four bytes.
stores one byte data It's a number which has the address in memory where a
character (char) lives.
A variable has 3 things : A pointer doesn't have any data in themself, they "point"
int <- type,x <- name,=3 <- data to a variable.Like : int x = 3; int *y = x
8
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Operators
There are two special operators which are used with Pointers: ‘*’ and ‘&’.
The ‘&’ (address operator) operator is a unary operator and it returns the
memory address of the operand. For example:
int value, *ptr; This statements place the memory address of ‘value’
ptr = & value; into ‘ptr’.
This address is the computer’s internal location of the variable ‘value’ and has
nothing to do with the values stored in the variable ‘value’.
The ‘&’ operator can be thought of as returning “the address of”.
Therefore ptr receives the address of value. Referring back, the value
of ‘var’ is 500 and it uses the memory location 1000 to store this value. After
this assignment, ‘ptr’ will have the value 1000.
9
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Operators
The second pointer operator, ‘*’, is the complement of ‘&’.
It is a unary operator, which is used to access the value of the variable to which
the pointer points.
Consider the code, where we will just assume that the variable var1 is stored at
the memory address 1000.
main( )
{ var2 = &var1 (var2 contains value 1000)
int var1, *var2, temp; temp=* var2 (temp contains 500 not
1000)
var1=500;
var2=&var1;
temp=*var2; The ‘*’ operator van be thought of as
printf(“%d %d %d”,var1, var2, temp);
“at the address”
}
10
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Operators
Both ‘*’ and ‘&’ have a higher precedence than all arithmetic operators expect
the unary minus.
They share the same precedence as the unary minus.
* and & are inverses - They cancel each other out
11
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Operators example
example:
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets address of y */
Now yPtr “points to” y, *yptr returns y (because yptr points to
y)
y yptr y
5 500000 600000 600000 5
yPtr
Address of y
is value of
yptr
12
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Operators example
main( )
{
int var=500, *ptr_var;
ptr_var=&var;
var1=500;
Program
var2=&var1;
temp=*var2;
printf(“\n The value %d is stored at address %u:”, var, &var);
printf(“\n The value %u is stored at address: %u:”, ptr_var, &ptr_var);
printf(“\n The value %d is stored at address: %u:”, *ptr_var, ptr_var);
}
The value 500 is stored at address : 65500
output The value 65500 is stored at address : 65502
The value 500 is stored at address : 65500
13
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 13
Pointers
Conclusions:
The contents of a memory location can be obtained by using *(pointer variable)
Since Pointer variable is also a variable, its address can be printed by prefixing it
with &.
Since integer occupies 2 bytes of memory. Hence value of a variable is stored at
65500 and the compiler allots the next memory location 65502 to other
variable.
Pointer variable stores an integer value.
*(&var) gives the same value as var. (value stored at the address of the variable
‘var’).
14
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Assigning values to Pointers
Values can be assigned to pointers through the & operator.
where the address of var is stored in the pointer ptr_var. ptr_var = &var;
ptr_var2 = &var2; It is also possible to assign values to pointers through
ptr_var = &var; another pointer pointing to a data item of the same type.
ptr_var2 = ptr_var ;
A NULL value can also assigned to a pointer either
#define NULL 0
through figurative constant or zero. ptr_var = NULL;
or ptr_var = 0;
15
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Assigning values to Pointers
Variables can be assigned value through their pointers
int var;
as well. This will assign 10 to the variable var. ptr_var = &var;
*ptr_var = 10;
It is important to assign values to pointer variables before using them; else they
point to any junk memory location.
16
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Arithmetic
Addition and Subtraction are the only operations, which can be performed on
pointers.
Let var be an integer type having a value 500 and stored int var, *ptr_var;
at the address 1000. Then ptr_var has the value 1000 ptr_var = &var;
var = 500;
stored in it.
Since integers are 2 bytes long, after the declaration: ptr_var++
ptr_var will contain 1002 and not 1001. This means that ptr_var is now pointing
to the integer stored at the address 1002.
Each time ptr_var is incremented, it will point to the next integer and since
integers are 2 bytes long, ptr_var will be incremented by 2. The same is true for
decrement also.
17
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Arithmetic contd.
+ + ptr_var or ptr_var + + Points to next integer after var
- - ptr_var or ptr_var - - Points to integer previous to var
ptr_var + I Points to ith integer after var
ptr_var - I Points to ith integer before var
Will increment var by 1. We know that the precedence of
the operator ++ is more compared to the * operator. So in
+ + * ptr_var or (ptr_var) + + this case if the expression is evaluated, the value of the
variable pointed by the pointer is incremented first and
then it is accessed using the * operator.
Will fetch the value of the next integer after var. As
discussed for the above case, in this case the pointer is
+ + * ptr_var or (ptr_var) + + incremented first to point to the next memory location
and then the value is accessed. This again happens
because the precedence of + + is higher as compared to *.
18
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Arithmetic contd.
Each time a pointer is incremented, it points to the memory location of the next
element of its base type.
Each time it is decremented, it points to the location of the previous element.
With pointers to characters, this appears normal, because generally characters
occupy 1 byte per character.
However, all others pointers will increase or decrease depending on the length
of the data type they are pointing to.
1000 1000 1001 1000 1003
1001 1002 1003 1004 1007
1002 1004 1005 1008 1011
1003 1006 1007 1012 1015
Char memory Integers memory Float memory
allocation allocation allocation
19
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 13
Pointers Pointer Arithmetic contd.
In addition to the increment and decrement operators, Integers can be Added
to and Subtracted from Pointers.
Besides Addition and Subtraction of an integer, none of the other Arithmetic
operations can be performed on Pointers.
To be specific, Pointers cannot be multiplied or divided.
Also, float or double type cannot be added to or subtracted from Pointers.
20
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Arithmetic contd.
Adding a number Subtracting Subtracting from Pointer Comparing two Pointers
main() main() main() main()
{ { { {
int i=4,*j,*k; int i=4,*j,*k;
j=&i; j=&i; int arr[]={10,20,30,45}; int arr[]={10,20,36,72,36};
printf("%d",j); printf("%d",j); int *i,*j; int *i,*j;
j=j+1; j=j-2; i=&arr[2];
printf("\n%d",j); printf("\n%d",j); i=&arr[1]; j=(arr+2);
j=j+9; j=j-5; j=&arr[3]; if(i==j)
printf("\n%d",j); printf("\n%d",j); printf(“same location");
k=j+3; k=j-6; printf("\n%d",j-i); else
printf("\n%d",k); printf("\n%d",k); printf("\n%d",*j - *i); printf(“not same location");
} } } }
8684 8684
8686 8680 2 Same Location
8704 8670 25
8710 8658
21
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Comparison
Two Pointers can be compared in a relational expression.
However, this is possible only if both of them point to variables of the same
type.
Consider that ptr_a and ptr_b are two pointer variables, which point to data
elements a and b.
Also if ptr_begin and ptr_end point to members of the same array then,
ptr_end - ptr_begin
will give difference in bytes between the storage locations to which they point.
22
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointer Comparison
ptr_a < ptr_b Returns true provided a is stored before b
ptr_a > ptr_b Returns true provided a is stored after b
ptr_a <= ptr_b Returns true provided a is stored before b or ptr_a and ptr_b point to
the same location
ptr_a >= ptr_b Returns true provided a is stored after b or ptr_a and ptr_b point to
the same location
ptr_a == ptr_b Returns true provided both pointers ptr_a and ptr_b point to the same
location
ptr_a != ptr_b Returns true provided both pointers ptr_a and ptr_b point to different
data elements but of the same type.
ptr_a != NULL Returns true if ptr_a is assigned NULL value(zero).
23
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointers as Function Arguments
Pointers are passed to a function as arguments, within the called routine of the
program, to access variables whose scope does not extend beyond the calling
function.
When a Pointer is passed to a function, the address of a data item is passed to
the function making it possible to freely access the contents of that address
from within the function.
The function as well as the calling routine recognizes any change made to the
contents of the address.
In this way, function arguments permit data-items to be altered in the calling
routine, enabling a two-way modification of data between the calling routine
and the function.
24
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Pointers as Function Arguments contd.
When the function arguments are pointers or arrays, a call by reference is
made to the function as opposed to a call by value for the variable arguments.
Formal arguments of a function, which are Pointers, are preceded by an
asterisk (*), just like pointer variable declarations, indicating them to be
pointers.
Actual pointer arguments in a function call must either be declared as pointers
or as referred variables (&var, where int var=5)
25
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 13
Pointers Call by Reference example
Program to swap two values void main( )
{
using Call by Reference. void swap(int *u, int *v); /* Function Prototype */
int x=15, y=20;
Values are passed as printf(“Before interchanging x=%d and y=%d”, x, y);
swap(&x, &y); /*Passing addresses of x and y */
*u = &x
printf(“After interchanging x=%d and y=%d”, x, y);
*v = &y }
Now the values are interchanged
void swap(int *u, int *v)
through the pointers {
int temp;
Output: temp=*u;
*u=*v;
Before interchanging x=15 and y=20 *v=temp;
return;
After interchanging x=20 and y=15 }
26
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 13
Pointers Call by Reference example
In this program the address of void main( )
String “Pointer” is passed to {
void getstr(char *ptr_str, int *ptr_int);
function using Pointer pstr,
int var=5;
address of var along with it. char *ptrstr=“Pointer”;
Value of var is modified in the getstr(pstr, &var); /*Passing addresses of x and y */
called function and printed. printf(“After modification var value is %d”, var);
}
The modified value of var is
also reflected in main also. void getstr(char *ptr_str, int *ptr_int)
{
Output: printf(“%s\n”, ptr_str);
Pointer *ptr_str=6;
After modification var value is 6 }
27
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Next Session
Pointers and Arrays
Pointers and Strings
Array of Pointers
Array of Pointers to Strings
Pointers and Functions
Multiple Indirection
Dynamic Memory Allocation
Thank You
28
20 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]