# Chapter 9- Pointers and Runtime Binding¶

In [1]:
from ctypes import c_int, pointer
a=c_int(100)
b=c_int(200)
c=c_int(300)
print 'Address', hex(id(pointer(b))), 'contains value', b.value
print 'Address', hex(id(pointer(c))), 'contains value', c.value

Address 0x3663448L contains value 100


## Example-initptr.cpp, Page no-296¶

In [1]:
from ctypes import c_int, pointer
var1=c_int(10)
var2=c_int(20)
iptr=pointer(var1)
print 'Address and contents of var1 is', hex(id(iptr)), 'and', iptr[0]
iptr=pointer(var2)
print 'Address and contents of var2 is', hex(id(iptr)), 'and', iptr[0]
iptr[0]=125
var1=iptr[0]*1

Address and contents of var1 is 0x364f248L and 10
Address and contents of var2 is 0x364f4c8L and 20


## Example-swap.cpp, Page no-298¶

In [1]:
from ctypes import c_float, pointer
def swap(pa, pb):
temp=pa[0]
pa[0]=pb[0]
pb[0]=temp
a=float(raw_input("Enter real number <a>: "))
b=float(raw_input("Enter real number <b>: "))
a=c_float(a)
b=c_float(b)
pa=pointer(a)
pb=pointer(b)
swap(pa, pb)
print "After swapping......"
print "a contains %0.1f" %(a.value)
print "b contains %0.1f" %(b.value)

Enter real number <a>: 10.5
Enter real number <b>: 20.9
After swapping......
a contains 20.9
b contains 10.5


## Example-voidptr.cpp, Page no-300¶

In [1]:
from ctypes import c_int, c_float, pointer
i1=c_int(100)
f1=c_float(200.5)
vptr=pointer(i1)
print "i1 contains", vptr[0] #value stored in address pointed by vptr
vptr=pointer(f1)
print "i1 contains", vptr[0]

i1 contains 100
i1 contains 200.5


## Example-ptrarr1.cpp, Page no-303¶

In [1]:
a=[int]
n=int(raw_input("Size of array? "))
print "Array elements ?"
for i in range(n):
a.append(int(raw_input()))
ptr=a
small=ptr[1]
for i in range(2, n+1):
if small>ptr[i]:
small=ptr[i]
i+=1 #pointer arithmetic
print "Smallest element is", small

Size of array? 5
Array elements ?
4
2
6
1
9
Smallest element is 1


## Example-newhand.cpp, Page no-305¶

In [1]:
size=int(raw_input("How many bytes to be allocated: "))
try:
data=[int]*size
print "Memory allocation success, address =", hex(id(data))
except:
print "Could not allocate. Bye..."
del data

How many bytes to be allocated: 300
Memory allocation success, address = 0x3716188L


## Example-ptr2ptr.cpp, Page no-306¶

In [6]:
data=c_int()
iptr=pointer(data)
ptriptr=pointer(iptr) #pointer to a pointer
iptr[0]=100
print "The variable 'data' contains", data.value
ptriptr[0][0]=200
print "The variable 'data' contains", data.value
data.value=300
print "ptriptr is pointing to", ptriptr[0][0]

The variable 'data' contains 100
The variable 'data' contains 200
ptriptr is pointing to 300


## Example-big.cpp, Page no-308¶

In [1]:
from ctypes import c_int, pointer
def FindBig(pa, pb, pbig):
if pa[0]>pb[0]:
pbig[0]=pa[0]
else:
pbig[0]=pb[0]
return pbig
a=c_int()
b=c_int()
big=pointer(c_int())
a, b=[int(x) for x in raw_input("Enter two integers: ").split()]
pa=[a]#pointer to a
pb=[b]#pointer to b
big=FindBig(pa, pb, big)
print "The value as obtained from the pointer:", big[0]

Enter two integers: 10 20
The value as obtained from the pointer: 20


## Example-sortptr.cpp, Page no-309¶

In [1]:
from ctypes import c_int, c_char_p
def SortByPtrExchange(person, n):
for i in range(n-1):
flag=1
for j in range(n-1-i):
if person[j]>person[j+1]:
flag=0
temp=person[j]
person[j]=person[j+1]
person[j+1]=temp
if flag:
break
n=c_int(0)
choice=c_char_p()
person=[[c_char_p]*100]*40
while(1):
person[n.value]=raw_input("Enter name: ")
n.value+=1
choice=raw_input("Enter another(y/n)? ")
if choice!='y':
break
print "Unsorted list: "
for i in range(n.value):
print person[i]
SortByPtrExchange(person, n.value)
print "Sorted list: "
for i in range(n.value):
print person[i]
for i in range(n.value):
del person[i]

Enter name: Tejaswi
Enter another(y/n)? y
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-show.cpp, Page no-311¶

In [2]:
def show(a, m):
c=a
for i in range(m):
for j in range(3):
print c[i][j],
print ""
c=[(1, 2, 3), (4, 5, 6)] #initialization of a 2D array
show(c, 2)

1 2 3
4 5 6


## Example-matrix.cpp, Page no-313¶

In [5]:
def MatAlloc(row, col):
p=[[int]*col]*row #dynamic array
return p
def MatRelease(p, row):
for i in range(row):
del p[i]
del p
for i in range(row):
for j in range(col):
print  "Matrix[", i, ",", j, "] = ? ",
a[i][j]=int(raw_input())
def MatMul(a, m, n, b, p, q, c):
if n!=p:
print "Error: Invalid matrix order for multiplication"
return
for i in range(m):
for j in range(q):
c[i][j]=0
for k in range(n):
c[i][j]+=a[i][k]*b[k][j]
def MatShow(a, row, col):
for i in range(row):
print ""
for j in range(col):
print a[i][j],
print "Enter Matrix A details..."
m=int(raw_input("How many rows ? "))
n=int(raw_input("How many columns ? "))
a=MatAlloc(m, n)
print "Enter Matrix B details..."
p=int(raw_input("How many rows ? "))
q=int(raw_input("How many columns ? "))
b=MatAlloc(p, q)
c=MatAlloc(m, q)
MatMul(a, m, n, b, p, q, c)
print "Matrix C = A * B ...",
MatShow(c, m, q)

 Enter Matrix A details...
How many rows ? 3
How many columns ? 2
Matrix[ 0 , 0 ] = ? 1
Matrix[ 0 , 1 ] = ? 1
Matrix[ 1 , 0 ] = ? 1
Matrix[ 1 , 1 ] = ? 1
Matrix[ 2 , 0 ] = ? 1
Matrix[ 2 , 1 ] = ? 1
Enter Matrix B details...
How many rows ? 2
How many columns ? 3
Matrix[ 0 , 0 ] = ? 1
Matrix[ 0 , 1 ] = ? 1
Matrix[ 0 , 2 ] = ? 1
Matrix[ 1 , 0 ] = ? 1
Matrix[ 1 , 1 ] = ? 1
Matrix[ 1 , 2 ] = ? 1
Matrix C = A * B ...
2 2 2
2 2 2
2 2 2


## Example-3ptr.cpp, Page no-315¶

In [2]:
arr=[((2, 1), (3, 6), (5, 3)), ((0, 9), (2, 3), (5, 8))]
print hex(id(arr))
print hex(id(arr[0]))
print hex(id(arr[0][0]))
print arr[0][0][0]
print hex(id(arr))
print hex(id(arr[0]))
print hex(id(arr[0][1]))
print arr[0][0][0]+1
for i in range(2):
for j in range(3):
for k in range(2):
print "arr[",i,"][", j, "][", k, "] = ", arr[i][j][k]

0x3729e88L
0x3652ab0L
0x364e388L
2
0x3729e88L
0x3652ab0L
0x364e6c8L
3
arr[ 0 ][ 0 ][ 0 ] =  2
arr[ 0 ][ 0 ][ 1 ] =  1
arr[ 0 ][ 1 ][ 0 ] =  3
arr[ 0 ][ 1 ][ 1 ] =  6
arr[ 0 ][ 2 ][ 0 ] =  5
arr[ 0 ][ 2 ][ 1 ] =  3
arr[ 1 ][ 0 ][ 0 ] =  0
arr[ 1 ][ 0 ][ 1 ] =  9
arr[ 1 ][ 1 ][ 0 ] =  2
arr[ 1 ][ 1 ][ 1 ] =  3
arr[ 1 ][ 2 ][ 0 ] =  5
arr[ 1 ][ 2 ][ 1 ] =  8


## Example-ptrinc.cpp, Page no-317¶

In [3]:
ia=[2, 5, 9]
ptr=ia
for i in range(3):
print ptr[i],
i+=1

2 5 9


## Example-strfunc.cpp, Page no-318¶

In [2]:
temp=raw_input("Enter string1: ")
s1=temp
temp=raw_input("Enter string2: ")
s2=temp
print "Length of string1:", len(s1) #string length
s3=s1+s2 #string concatenation
print "Strings' on concatenation:", s3
print "String comparison using..."
print "Library function:", s1>s2 # - operator is not supppoertd with string operands in python
print "User's function:", s1>s2# - operator is not supppoertd with string operands in python

Enter string1: Object
Enter string2: Oriented
Length of string1: 6
Strings' on concatenation: ObjectOriented
String comparison using...
Library function: False
User's function: False


## Example-rfact.cpp, Page no-322¶

In [1]:
def fact(num):
if num==0:
return 1
else:
return num*fact(num-1)
ptrfact={}
ptrfact[0]=fact #function pointer
n=int(raw_input("Enter the number whose factorial is to be found: "))
f1=ptrfact[0](n)
print "The factorial of", n, "is", f1
print "The factorial of", n+1, "is", ptrfact[0](n+1)

Enter the number whose factorial is to be found: 5
The factorial of 5 is 120
The factorial of 6 is 720


## Example-rmain.cpp, Page no-323¶

In [1]:
#this program will print hello infinite number of times
def main():
p={}
print "Hello...",
p[0]=main #function pointer to main()
p[0]()
main()


## Example-passfn.cpp, Page no-324¶

In [1]:
def small(a, b):
return a if a<b else b
def large(a, b):
return a if a>b else b
def select(fn, x, y):
value=fn(x, y)
return value
ptrf={}
m, n=[int(x) for x in raw_input("Enter two integers: ").split()]
high=select(large, m, n) #function as parameter
ptrf[0]=small #function pointer
low=select(ptrf[0], m, n) #pointer to function as parameter
print "Large =", high
print "Small =", low

Enter two integers: 10 20
Large = 20
Small = 10


## Example-bdate.cpp, Page no-326¶

In [1]:
from ctypes import Structure, c_int, POINTER
class date(Structure):
_fields_=[('data', c_int), ('month', c_int), ('year', c_int)]
def show(self):
print '%s-%s-%s' %(self.day, self.month, self.year)
dp.day=int(raw_input("Enter day: "))
dp.month=int(raw_input("Enter month: "))
dp.year=int(raw_input("Enter year: "))
d1=date()
dp1=POINTER(date)
dp2=POINTER(date)
print "Enter birthday of boy..."
dp2=date()
print "Enter birthday of girl..."
print "Birth date of boy:",
dp1=d1
dp1.show()
print "Birth date of girl:",
dp2.show()

Enter birthday of boy...
Enter day: 14
Enter month: 4
Enter year: 71
Enter birthday of girl...
Enter day: 1
Enter month: 4
Enter year: 72
Birth date of boy: 14-4-71
Birth date of girl: 1-4-72


## Example-list.cpp, Page no-329¶

In [1]:
from ctypes import Structure
class LIST(Structure):
data=int
Next=None
def InsertNode(data, first):
newnode=LIST()
newnode.data=data
newnode.Next=first
return newnode
def DeleteNode(data, first):
current=LIST()
pred=LIST()
if first==None:
print "Empty list"
return first
pred=current=first
while(1):
if current.data==data:
if current==first:
first=current.Next
current=current.Next
else:
pred.Next=current.Next
current=current.Next
del current
return first
current=current.Next
return first
def DisplayList(first):
List=LIST()
List=first
while(1):
print "->", List.data,
if List.Next==None:
break
List=List.Next
print ""
List=LIST()
List=None
while(1):
choice=int(raw_input("List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: "))
if choice==1:
data=int(raw_input("Enter data for node to be created: "))
List=InsertNode(data, List)
elif choice==2:
print "List Contents:",
DisplayList(List)
elif choice==3:
data=int(raw_input("Enter data for node to be delete: "))
List=DeleteNode(data, List)
elif choice==4:
print "End of Linked List Computation !!."
break
else:

Linked-list manipulation program...
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 1
Enter data for node to be created: 5
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 1
Enter data for node to be created: 7
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 1
Enter data for node to be created: 3
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 2
List Contents: -> 3 -> 7 -> 5
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 3
Enter data for node to be delete: 7
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 2
List Contents: -> 3 -> 5
List operation, 1- Insert, 2- Display, 3-Delete, 4-Quit: 4
End of Linked List Computation !!.


## Example-wild1.cpp, Page no-332¶

In [1]:
p=[int]*10 #uninitialized integer pointer
for i in range(10):
print p[i],

<type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'int'> <type 'int'>


## Example-wild2.cpp, Page no-332¶

In [1]:
name="Savithri"
print name

Savithri


## Example-wild3.cpp, Page no-333¶

In [1]:
def nameplease():
name="Savithri"
return name
ch='X'
return ch
print "Name =", p1
print "Char =", p2

Name = Savithri
Char = X


## Example-wild4.cpp, Page no-334¶

In [1]:
p1=str
def temp():
name="Savithri"
global p1
p1=name
temp()
print "Name =", p1

Name = Savithri


## Example-1, Page no-335¶

In [1]:
Str="Programming"
count=0
str_ptr=Str[0]
while(count+1<len(Str)):
count+=1
str_ptr=Str[count]
count+=1
print "Number of characters in the word Programming =", count

Number of characters in the word Programming = 11


## Example-2, Page no-335¶

In [1]:
def sort(x):
for k in range(SIZE-1):
i=0
while i<=(SIZE-k-2):
if x[i]>x[i+1]:
x[i], x[i+1]=x[i+1], x[i]
i+=1
return x
SIZE=10
a=[4,59,84,35,9,17,41,19,2,21]
ptr=a
temp=ptr
print "Given array elements:"
for i in range(SIZE):
print temp[i],
ptr=sort(ptr)
temp=ptr
print "\nSorted array elemnets:"
for i in range(SIZE):
print temp[i],

Given array elements:
4 59 84 35 9 17 41 19 2 21
Sorted array elemnets:
2 4 9 17 19 21 35 41 59 84