# Chapter 8: Pointers¶

## Example getaddr.c, page no. 261¶

#### Note: There is no concept of pointers in Python. Hence, output may not match for some of the examples.¶

In [4]:
a = 100
b = 200
c = 300

print "Address: %x contains value: %i" %(a, a)
print "Address: %x contains value: %i" %(b, b)
print "Address: %x contains value: %i" %(c, c)

Address: 64 contains value: 100


## Example 8.1, page no. 263¶

In [8]:
i = 7
f = 10.5
c = 'A'
print "%d is stored at address %u" %(i, id(i))
print "%f is stored at address %u" %(f, id(f))
print "%c is stored at address %u" %(c, id(c))

7 is stored at address 41297768
10.500000 is stored at address 53588120
A is stored at address 140471220157656


## Example 8.2, page no. 263¶

In [10]:
var1 = 10
var2 = 20
iptr = id(var1)
print "Address and contents of var1 is: %d & %d" %(iptr, var1)
iptr = id(var2)
print "Address and contents of var1 is: %d & %d" %(iptr, var2)

Address and contents of var1 is: 41297696 & 10
Address and contents of var1 is: 41297456 & 20


## Example derefer.c, page no. 265¶

In [13]:
#note: we have used var1 instead of iptr because there is no point of pointer in python. Hence, instead of *iptr
#we have to refer to the same variable
var1 = 0
iptr = id(var1)
var1 = 25
var1 += 10
print "Variable var1 contains %i " %var1
var2 = var1
print "Variable var2 contains: %i" %var2
iptr = id(var2)
var2 += 20
print "Variable var2 now contains: %i" %var2

Variable var1 contains 35
Variable var2 contains: 35
Variable var2 now contains: 55


## Example 8.3, page no. 267¶

In [14]:
a = 5
b = 10
ptr = id(a)
print "Initial values of a & b"
print "a = %d" %a
print "b = %d" %b
b = a
print "Changed values of a & b"
print "a = %d" %a
print "b = %d" %b
print "Address of variable is ", id(a)
print "Address of variable is ", id(b)
print "Address assigned to pointer ptr is ", id(ptr)
print "Value pointer ptr access is ", a

Initial values of a & b
a = 5
b = 10
Changed values of a & b
a = 5
b = 5
Address assigned to pointer ptr is  51460736
Value pointer ptr access is  5


## Example 8.4, page no. 268¶

In [3]:
def swap(d1, d2):
return d2, d1

print "Enter 2 real numbers:"
data1 = float(raw_input("num1: "))
data2 = float(raw_input("num2: "))

print "Data1 contains: ", data1
print "Data2 contains: ", data2
data1, data2 = swap(data1, data2)
print "After swapping....."
print "Data1 contains: ", data1
print "Data2 contains: ", data2

Enter 2 real numbers:
num1: 23.55
num2: -65.73
Data1 contains:  23.55
Data2 contains:  -65.73
After swapping.....
Data1 contains:  -65.73
Data2 contains:  23.55


## Example voidptr.c, page no. 270¶

In [4]:
i1 = 100
f1 = 200.5
vptr = id(i1)
print "i1 contains ", i1
vptr = id(f1)
print "f1 contians ", f1

i1 contains  100
f1 contians  200.5


## Example 8.5, page no. 271¶

In [5]:
#the way it is given in the textbook is not possible as there is no concept of pointers in Python
a = []
print "Size of array ?"
n = int(raw_input())
print "Array elements ?"
for i in range(n):
a.append(int(raw_input()))
small = min(a)
print "The smallest element is ", small

Size of array ?
6
Array elements ?
-9
12
-23
5
0
-77
The smallest element is  -77


## Example 8.6, page no. 272¶

In [7]:
a = 5
b = 10
ptr1 = id(a)
ptr2 = id(b)

c = a + b
d = a/b*7

print "Addresses of variables 'a' and 'b': "
print "a: ", ptr1
print "b: ", ptr2

print "Addresses of pointers 'ptr1' and 'ptr2' hold: "
print "ptr1: ", ptr1
print "ptr2: ", ptr2

print "values of 'a', 'b', 'c', 'd': "
print "a = %2d   b = %2d  c = %2d  d = %2d" %(a,b,c,d)
print "Values accessed by pointers 'ptr1' and 'ptr2': "
print "ptr1: ", ptr1
print "ptr2: ", ptr2

Addresses of variables 'a' and 'b':
a:  37181336
b:  37181216
Addresses of pointers 'ptr1' and 'ptr2' hold:
ptr1:  37181336
ptr2:  37181216
values of 'a', 'b', 'c', 'd':
a =  5   b = 10  c = 15  d =  0
Values accessed by pointers 'ptr1' and 'ptr2':
ptr1:  37181336
ptr2:  37181216


## Example farptr.c, page no. 275¶

In [8]:
# not possible in Python


## Example ptriptr.c, page no. 275¶

In [9]:
data = 0
iptr = id(data)
ptriptr = id(iptr)
data = 100
print "Variable 'data' contains: ", data
ptriptr = 200
print "Variable 'data' contains: ", data
#value of data won't change as there is no pointer
data = 300
print "ptriptr is pointing to: ", data

Variable 'data' contains:  100
Variable 'data' contains:  100
ptriptr is pointing to:  300


## Example on page no. 277¶

In [11]:
iarray = [1, 2, 3, 4, 5]
for i in range(5):
print id(iarray[i]), iarray[i]

37181432 1
37181408 2
37181384 3
37181360 4
37181336 5


## Example on page no. 279¶

In [26]:
def sort_it(b):
return sorted(b)

a = []
print "Eneter the number of elements in the array (lessthan 21): "
n = int(raw_input())
print "Enter the elements: "
for i in range(n):
a.append(int(raw_input()))
arr = sort_it(a)
print "The sorted array: "
for ele in arr:
print ele,

Eneter the number of elements in the array (lessthan 21):
5
Enter the elements:
-4
7
4
0
1
The sorted array:
-4 0 1 4 7


## Example 8.7, page no. 280¶

In [29]:
def SortByPtrExchange(person):
return sorted(person)
choice = 'y'
person = []
while choice == 'y':
print "Enter Name: "
person.append(raw_input())
print "Enter another ? (y/n)"
choice = raw_input()
print "Unsorted list: "
for per in person:
print per
person = SortByPtrExchange(person)
print "Sorted List: "
for per in person:
print per

Enter Name:
Tejaswi
Enter another ? (y/n)
y
Enter Name:
Enter another ? (y/n)
y
Enter Name:
Prakash
Enter another ? (y/n)
y
Enter Name:
Sudeep
Enter another ? (y/n)
y
Enter Name:
Anand
Enter another ? (y/n)
n
Unsorted list:
Tejaswi
Prakash
Sudeep
Anand
Sorted List:
Anand
Prakash
Sudeep
Tejaswi


## Example argref.c, page no. 282¶

In [32]:
def Add10(studentmarks):
studentmarks += 10
return studentmarks
Marks = 25
print "Value of Marks = %d" %Marks
print "Value of Marks after execution = %d" %Marks

Value of Marks = 25
Value of Marks after execution = 35


## Example accfunc.c, page no. 283¶

In [33]:
Max = 5
global Max
for i in range(Max):
studentmarks[i] += 10
return studentmarks
Marks = [25, 43, 70, 80, 76]
for j in range(Max):
print "Marks[%d] = %d" %(j, Marks[j])

Marks[0] = 35
Marks[1] = 53
Marks[2] = 80
Marks[3] = 90
Marks[4] = 86


## Example 8.8, page no. 285¶

In [1]:
def exchange(x, y):
return y, x
print "Program swaps values of the variables 'a' and 'b'"
print "Values of a & b: "
a = int(raw_input("a: "))
b = int(raw_input("b: "))
print "a: %5d \t b = %5d" %(a, b)
x, y = exchange(a, b)
print "After swapping: "
print "a = %5d \t b = %5d" %(x, y)

Program swaps values of the variables 'a' and 'b'
Values of a & b:
a: 78
b: 196
a:    78 	 b =   196
After swapping:
a =   196 	 b =    78


## Example on page no. 287¶

In [36]:
#not possible in Python. Hence, skipping


## Example on page no. 288¶

In [38]:
arr = [1, 2, 3]
ptr = id(arr)
for i in range(3):
print "%d %d" %(id(i), arr[i])

37181456 1
37181432 2
37181408 3


## Example 8.9, page no. 289¶

In [40]:
arr = [1, 2, 3, 4, 5]
for ele in arr[::-1]:
print ele,

5 4 3 2 1


## Example 8.10, page no. 289¶

In [42]:
arr = [-1, -2, -3, -4, -5]
p = arr
arr = arr[::-1]
p = p[::-1]
for i in range(len(arr)):
print arr[i], "\t", p[i]

-5 	-5
-4 	-4
-3 	-3
-2 	-2
-1 	-1


## Example on page no. 290¶

In [44]:
ia = [2, 5, 9]
ptr = ia
for ele in ptr:
print ele,

2 5 9


## Example 8.11, page no. 291¶

In [47]:
def FindBig(x, y):
return x if x > y else y
print "Enter two integers: "
a = int(raw_input("int1: "))
b = int(raw_input("int2: "))
big = FindBig(a, b)
print "Variable name \t address of the variable \t value"
print "a \t\t %d \t\t\t %d"%(id(a), a)
print "The bigger of the two integers"
print "big \t\t %d \t\t\t %d" %(id(big), big)
print "The value as botained form pointer: ", big

Enter two integers:
int1: 5
int2: 7
Variable name 	 address of the variable 	 value
a 		 37181336 			 5
The bigger of the two integers
big 		 37181288 			 7
The value as botained form pointer:  7


## Example string1.c, page no. 292¶

In [53]:
city = "Bangalore"
i = 0
for i in range(len(city)):
print id(city[i]), "\t\t\t ", city[i], city[i], city[i]

Address 				 Contents
140069470495088 			  B B B
140069470360920 			  a a a
140069470570416 			  n n n
140069470363320 			  g g g
140069470360920 			  a a a
140069470363160 			  l l l
140069470363280 			  o o o
140069470569656 			  r r r
140069470571696 			  e e e


## Example on page no. 293¶

In [55]:
chArr = "Pointer and Strings"
chPtr = chArr
print "Contents pointed by the pointer chPtr is: ", chPtr

Contents pointed by the pointer chPtr is:  Pointer and Strings


## Example on page no. 293¶

In [62]:
def usrstrlen(ptr):
ln = 0
for ele in ptr:
ln += 1
return ln
s1 = "Good"
print "Length of string using standard library function",
print len(s1)
length = usrstrlen(s1)
print "Length of string using user defined function ", length

Length of string using standard library function 4
Length of string using user defined function  4


## Example 8.12, page no. 294¶

In [63]:
print "Enger the string to find it's length"
string = raw_input()
print "String is: ", string
print "It's length is : ", len(string)

Enger the string to find it's length
Visvesvaraya College
String is:  Visvesvaraya College
It's length is :  20


## Example on page no. 294¶

In [66]:
def usrstrcpy(s):
s2 = []
for ele in s:
s2.append(ele)
s2 = ''.join(s2)
return s2
s1 = "Good"
s2 = s1
print "Copied string using normal assignment is ", s2
s2 = usrstrcpy(s1)
print "Copied string using user defined function is ", s2

Copied string using normal assignment is  Good
Copied string using user defined function is  Good


## Example on page no. 295¶

In [70]:
def usrstrcat(s2, s1):
return s1 + s2

s1 = "Good"
s2 = " Morning"
s3 = s1+s2
print "Concatenation using normal Python addition",
print s3
s1 = usrstrcat(s2, s1)
print "concatenation using user defined function is ", s1

Concatenation using normal Python addition Good Morning
concatenation using user defined function is  Good Morning


## Example on page no. 296¶

In [72]:
#only user defined way is possible in Python. Normal way would return either True or False only
s1 = "Good"
s2 = " Morning"
if s1 < s2:
r = -1
elif s1 > s2:
r = 1
else:
r = 0
print "Comparison of strings using user defined way is ", r

Comparison of strings using normal python way is  1


## Example on page no. 297¶

In [76]:
pet = ["lion", "cat"]
for i in range(len(pet)):
print id(pet[i]), pet[i]

52705200 lion
140069470362560 cat


## Example 8.13, page no. 298¶

In [78]:
st = "hello"
for i in range(len(st)):
print st[i], "\t", st[i], "\t", st[i], "\t", st[i]

h 	h 	h 	h
e 	e 	e 	e
l 	l 	l 	l
l 	l 	l 	l
o 	o 	o 	o


## Example 8.14, page no. 299¶

In [80]:
st = "Good Morning"
print st[3:]

d Morning


## Example 8.15, page no. 299¶

In [81]:
#not possible in Python. Skipping


## Example strchr.c, page no. 300¶

In [86]:
string = raw_input("Enter a string: ")
c = raw_input("Enter character to be searched: ")
try:
i = list(string).index(c)
print "%c was found in position %d" %(c, i)
except:
pass

Enter a string: House
Enter character to be searched: s
s was found in position 3


## Example strcspn.c, page no. 302¶

In [10]:
string1 = "0123456789"
string2 = "A47DCF8"
c = 0
for ele in string2:
if ele in string1:
index = string1.index(ele)
break

4


## Example strcspn.c, page no.303¶

In [11]:
string1 = "0123456789"
string2 = "A32DC014"
c = 0
for ele in string1:
for ele1 in string2:
if ele == ele1:
c += 1
print c

5


## Example strpbrk.c, page no. 303¶

In [1]:
import sys

print "Input two Strings: "
str1 = raw_input("Str1: ")
str2 = raw_input("Str2: ")

for ele in str1:
if ele in str2:
print "Character found: ", ele
sys.exit()

Input two Strings:
Str1: House
Str2: Sorrow
Character found:  o

An exception has occurred, use %tb to see the full traceback.

SystemExit

To exit: use 'exit', 'quit', or Ctrl-D.


## Example strstr.c, page no. 304¶

In [2]:
import sys

print "Input two Strings: "
str1 = raw_input("Str1: ")
str2 = raw_input("Str2: ")

if str2 in str1:
str1.index(str2)
print "String 2 is found at position 6 in string1"

Input two Strings:
Str1: I saw the cat click the mouse.
Str2: the
String 2 is found at position 6 in string1


## Example strtok.c, page no. 305¶

In [9]:
my_str = raw_input("Input a string, parts separated by , or ;")
print "The tokens found were: "
token = ''
for i in range(len(my_str)):
if my_str[i] == ',' or my_str[i] == ';':
if len(token) > 0:
print token
token = ''
else:
token = token + my_str[i]
print token

Input a string, parts separated by , or ;;abc,defgh;;hi,jklmn;op
The tokens found were:
abc
defgh
hi
jklmn
op


## Example 8.16, pag eno. 307¶

In [10]:
def func1(i, f):
print i, f
def func2(s):
print s

i = 5
f = 5.375
s = "string"
func1(i, f)
func2(s)

5 5.375
string


## Example on page no. 308¶

In [11]:
def fact(m):
if m == 1:
return 1
else:
return m*fact(m-1)
print "Enter the integer whose factorial is to be found: ",
n = int(raw_input())
ans = fact(n)
print "Factorial of ", n, " is ", ans

Enter the integer whose factorial is to be found: 8
Factorial of  8  is  40320


## Example on page no. 308¶

In [12]:
def large(b):
return max(b)
def small(b):
return min(b)
print "Enter the number of integers: ",
n = int(raw_input())
print "Enter the set of integers: "
a = []
for i in range(n):
a.append(int(raw_input()))
print "The largest integer is: ", large(a)
print "The smallest integer is: ", small(a)

Enter the number of integers: 5
Enter the set of integers:
5
-7
4
0
1
The largest integer is:  5
The smallest integer is:  -7


## Example 8.17, page no. 311¶

In [13]:
MAX = 20
def print_array(a):
print "The elements of the array are: "
for ele in a:
print ele,
print "Enter the number of elements: "
n = int(raw_input())
print "Enter the elements: "
a = []
for i in range(n):
a.append(int(raw_input()))
if n < 0 or n > MAX:
print "Invalid number of elements..."
else:
print_array(a)

Enter the number of elements:
5
Enter the elements:
1
2
3
4
5
The elements of the array are:
1 2 3 4 5


## Example 8.18, page no. 313¶

In [15]:
def upper(instr):
return instr.upper()
def lower(instr):
return instr.lower()
instr = raw_input("Input a string: ")
print "To upper or lower (u/l): "
inchar = raw_input()
if inchar == 'l':
print "The converted string is \n", lower(instr)
elif inchar == 'u':
print "The conveerted string is \n", upper(instr)
else:
print "Ivalid input..."

Input a string: UVCE, Bangalore
To upper or lower (u/l):
l
The converted string is
uvce, bangalore