Chapter 10: Pointers

Example 10.1, Page Number 431

In [1]:
var1 = 11                    #define and initialize three variables
var2 = 22
var3 = 33

print hex(id(var1))          #print the address of these variables
print hex(id(var2))
print hex(id(var3))
0x1bf5fa8L
0x1bf5ea0L
0x1bf5d98L

Example 10.2, Page Number 433

In [2]:
from ctypes import c_int,pointer,addressof

var1 = c_int(11)            #two integer variables
var2 = c_int(22)

print hex(id(var1)),'\n',hex(id(var2)),'\n'       #print addresses of variables

ptr = pointer(var1)                     #pointer to integer variable var1
print hex(addressof(ptr))               #print address of ptr

ptr = pointer(var2)                     #pointer to integer variable var2
print hex(addressof(ptr))               #print address of ptr

#in python, id(a) != addressof(pinter(a))
0x3681448L 
0x3681548L 

0x3681790L
0x3681810L

Example 10.3, Page Number 436

In [3]:
from ctypes import c_int,pointer

var1 = c_int(11)             #two integer variables
var2 = c_int(22)

ptr = pointer(var1)          #pointer to integer variable var1
print ptr[0]                 #print contents of pointer (11)

ptr = pointer(var2)          #pointer to integer variable var2
print ptr[0]                 #print contents of pointer (22)
11
22

Example 10.4, Page Number 437

In [4]:
from ctypes import c_int,pointer

var1 = c_int()             #integer variable

ptr = pointer(var1)        #set pointer to address of var1
ptr[0] = c_int(37)         #same as var1 = 37
var2 = ptr[0]              #same as var2 = var1

print var2                 #verify var2 is 37
37

Example 10.5, Page Number 439

In [5]:
from ctypes import c_int,pointer,c_float

intvar = c_int()               #define integer variable
flovar = c_float()             #define float variable

ptrint = pointer(intvar)
ptrflo = pointer(flovar)
ptrvoid = pointer(intvar)
ptrvoid = pointer(flovar)

Example 10.6, Page Number 440

In [6]:
intarray = [31,54,77,52,93]           #array

for j in range(5):                    #for each element
    print intarray[j]                 #print value
31
54
77
52
93

Example 10.7, Page Number 441

In [7]:
from ctypes import c_int

intarray = [31,54,77,52,93]           #array

arr = (c_int * len(intarray))(*intarray)        #pointer to intarray

for j in range(5):                    #for each element
    print arr[0 + j]                  #print value
31
54
77
52
93

Example 10.8, Page Number 443

In [8]:
from ctypes import c_int

intarray = [31,54,77,52,93]           #array

arr = (c_int * len(intarray))(*intarray)        #pointer to intarray

for j in range(5):                    #for each element
    print arr[0 + j]                  #print value
31
54
77
52
93

Example 10.9, Page Number 443

In [9]:
def centimize(v):
    v *= 2.54                       #convert inches to centimeters
    return v

var = 10.0                          #var has value of 10 inches
print 'var =',var,'inches'

var = centimize(var)                #change variable var to centimeters
print 'var =',var,'centimeters'
var = 10.0 inches
var = 25.4 centimeters

Example 10.10, Page Number 444

In [10]:
from ctypes import c_float,pointer

def centimize(ptrd):
    ptrd[0] *= 2.54                 #ptrd[0] is the same as var
 
var = 10.0                          #var has value of 10 inches
print 'var =',var,'inches'

var = c_float(10.0)

centimize(pointer(var))             #change variable var to centimeters
print 'var =',var.value,'centimeters'
var = 10.0 inches
var = 25.3999996185 centimeters

Example 10.11, Page Number 446

In [11]:
MAX = 5                                  #number of array element

def centimize(ptrd):
    for j in range(MAX):
        ptrd[0+j] *= 2.54                #ptrd points to elements of array

varray = [10.0,43.1,95.9,59.7,87.3]

centimize(varray)                        #change elements of array to cm

for j in range(MAX):                     #display new array values
    print 'varray[%d]=%.3f centimeter' %(j,varray[j])
varray[0]=25.400 centimeter
varray[1]=109.474 centimeter
varray[2]=243.586 centimeter
varray[3]=151.638 centimeter
varray[4]=221.742 centimeter

Example 10.12, Page Number 448

In [12]:
from ctypes import c_int,pointer

def order(numb1 ,numb2):              #orders two numbers
    if numb1[0] > numb2[0]:           #if 1st larger than 2nd
        temp = numb1[0]               #swap them
        numb1[0] = numb2[0]
        numb2[0] = temp
        
        
n1 = c_int(99);n2 = c_int(11)         #one pair ordered, one not
n3 = c_int(22);n4 = c_int(88)

order(pointer(n1) , pointer(n2))      #order each pair of numbers
order(pointer(n3) , pointer(n4))

print 'n1 =',n1.value              #print out all numbers
print 'n2 =',n2.value
print 'n3 =',n3.value
print 'n4 =',n4.value
n1 = 11
n2 = 99
n3 = 22
n4 = 88

Example 10.13, Page Number 449

In [13]:
def order(numb1 ,numb2):        #orders two numbers
    if numb1 > numb2:           #if 1st larger than 2nd
        temp = numb1            #swap them
        numb1 = numb2
        numb2 = temp
    return numb1,numb2
    
        
def bsort(ptr,n):
    for j in range(n-1):                      #outer loop
        for k in range(j+1,n,1):              #inner loop starts at outer
            ptr[j] ,ptr[k] = order(ptr[j] ,ptr[k])       #order the contents
            
            
            
N = 10                  #array size

arr = [37,84,62,91,11,65,57,28,19,49]        #test array

bsort(arr,N)            #sort the array

for j in range(N):      #print out sorted array
    print arr[j],'',
    
11  19  28  37  49  57  62  65  84  91 

Example 10.14, Page Number 452

In [14]:
str1 = "Defined as an array"             #two strings
str2 = "Defined as a pointer"

print str1                 #display both string
print str2

print str2[1:]             #str2 starts from "efined..."
Defined as an array
Defined as a pointer
efined as a pointer

Example 10.15, Page Number 453

In [15]:
def dispstr(ps):
    print ps        #display string str through ps
    
str = "Idle people have the least leisure."            #string

dispstr(str)         #display string
Idle people have the least leisure.

Example 10.16, Page Number 454

In [16]:
def copystr(dest,src):
    dest = src                 #copy string 
    return dest

str1 = "Self-conquest is the greatest victory."
str2 = ""                       #empty string

str2 = copystr(str2,str1)       #copy str1 to str2

print str2
Self-conquest is the greatest victory.

Example 10.17, Page Number 457

In [17]:
Days = 7            #number of variables in array

arrptrs = ["Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday"]

for j in range(Days):        #display every string
    print arrptrs[j]
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Example 10.18, Page Number 459

In [18]:
str = "Idle hands are the devil's workshop."
strlen = len(str)                                #get length of str

ptr = ["" for j in range(strlen + 1)]            #set aside memory: string + '\0'
ptr = str                 #copy str to new memory area ptr
  
print 'ptr =',ptr                 #show that ptr is now in str

del ptr
ptr = Idle hands are the devil's workshop.

Example 10.19, Page Number 462

In [19]:
class String:                        #user-defined string type
    def __init__(self,s):            #constructor
        self.__str = s               #copy argument to str
        
    def __del__(self):               #destructor
        print 'Deleting str'         #release memory
        
    def display(self):               #display the string
        print self.__str
        
        
        
s1 = String("Who knows nothing doubts nothing.")          #uses 1-arg constructor

print 's1 =',            #display string
s1.display()

del s1
s1 = Who knows nothing doubts nothing.
Deleting str

Example 10.20, Page Number 464

In [20]:
from ctypes import POINTER,Structure

class Distance(Structure):          #Distance class
    
    def getdist(self):              #get length from user
        self.__feet = input("\nEnter feet: ")
        self.__inches = input("Enter inches: ")
        
    def showdist(self):             #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
        
        
dist = Distance()                   #define a named Disatance object
dist.getdist()                      #access object member with dot operator
dist.showdist()

distptr = POINTER(Distance)         #points to Distance

distptr = dist                      

distptr.getdist()                   #access object members
distptr.showdist()
Enter feet: 10
Enter inches: 6.25
10 ' - 6.25 "

Enter feet: 6
Enter inches: 4.75
6 ' - 4.75 "

Example 10.21, Page Number 466

In [21]:
from ctypes import Structure,POINTER

class Distance(Structure):          #Distance class
    
    def getdist(self):              #get length from user
        self.__feet = input("Enter feet: ")
        self.__inches = input("Enter inches: ")
        
    def showdist(self):             #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
        
        
dist = Distance()
distptr = POINTER(Distance)

distptr = dist          

distptr.getdist()
distptr.showdist()
Enter feet: 10
Enter inches: 6.25
10 ' - 6.25 "

Example 10.22, Page Number 467

In [22]:
from ctypes import Structure

class person(Structure):                #class of persons
    
    def setName(self):                  #set the name
        self.__name = raw_input("Enter name: ")
        
    def printName(self):                #get the name
        print '   Name is :',self.__name
        
        
        
ob = [person() for j in range(100)]     #array of persons
persPtr = ob                            #array to persons
n = 0                                   #number of persons in array


while True:                             #put persons in array
    
    persPtr[n].setName()                #set person's name
    n += 1                              #count new person
    choice = raw_input('Enter another (y/n)? ')      #person ?
    
    if choice=='n':                     #quit on 'n'
        break
        
for j in range(n):                      #print names of all persons
    print 'person number',j+1
    persPtr[j].printName()
    
Enter name: Stroustrup
Enter another (y/n)? y
Enter name: Ritchie
Enter another (y/n)? y
Enter name: Kernighan
Enter another (y/n)? n
person number 1
   Name is : Stroustrup
person number 2
   Name is : Ritchie
person number 3
   Name is : Kernighan

Example 10.23, Page Number 469

In [23]:
class link:
    def __init__(self):
        self.data = None                    # contains the data
        self.next = None                    # contains the reference to the next node


class linklist:
    def __init__(self):
        self.first = None

    def additem(self, d):                   # add data item
        newlink = link()                    # make a new link
        newlink.data = d                    # give it data
        newlink.next = self.first           # it points to next link
        self.first = newlink                # now first points to this

    def display(self):
        current = self.first                # set ptr to first link
        while current:                      # quit on last link
            print current.data              # print data
            current = current.next          # move to next link


            

li = linklist()             # make linked list

li.additem(25)              # add four items to linked list
li.additem(36)
li.additem(49)
li.additem(64)

li.display()                # display entire list
64
49
36
25

Example 10.24, Page Number 474

In [24]:
from ctypes import Structure,POINTER

def order(numb1 ,numb2):        #orders two objects
    if numb1.getname() > numb2.getname():           #if the name of 1st larger than 2nd
        temp = numb1            #swap them
        numb1 = numb2
        numb2 = temp
    return numb1,numb2
    
        
def bsort(ptr,n):
    for j in range(n-1):                      #outer loop
        for k in range(j+1,n,1):              #inner loop starts at outer
            ptr[j] ,ptr[k] = order(ptr[j] ,ptr[k])       #order the contents
    return ptr


class person(Structure):                #class of persons
    
    def setName(self):                  #set the name
        self.__name = raw_input("Enter name: ")
        
    def printName(self):                #display the name
        print self.__name
        
    def getname(self):                  #returns the name
        return self.__name
    
    
    
    
ob = [person()]*100                     #array of persons
persPtr = POINTER(person)               #pointer to person
 
persPtr = ob                            #array of pointers to persons
n = 0                                   #number of persons in array

while True:                             #put persons in array
    
    persPtr[n] = person()
    persPtr[n].setName()                #set person's name
    
    n += 1                              #count new person
    
    choice = raw_input('Enter another (y/n)? ')           #person ?
    
    if choice=='n':                     #quit on 'n'
        break

        
print '\nUnsorted list:'
for j in range(n):                      #print names of all persons
    persPtr[j].printName()
    
    
persPtr = bsort(persPtr,n)              #sorts the content of array according to their name

print '\nSorted list:'
for j in range(n):                      #print names of all persons
    persPtr[j].printName()
Enter name: Washington
Enter another (y/n)? y
Enter name: Adams
Enter another (y/n)? y
Enter name: Jefferson
Enter another (y/n)? y
Enter name: Madison
Enter another (y/n)? n

Unsorted list:
Washington
Adams
Jefferson
Madison

Sorted list:
Adams
Jefferson
Madison
Washington

Example 10.25, Page Number 481

In [25]:
LEN = 80               #length of expression, in character
MAX = 40               #size of stack


class stack:
    
    def __init__(self):
        self.__st = [None]*MAX              #stack: array of chars
        self.__top = 0                      #number of top of stack
        
    def push(self,var):                     #put char on stack
        self.__top += 1
        self.__st[self.__top] = var
        
    def pop(self):                          #take char off stack
        x = self.__st[self.__top]
        self.__top -= 1
        return x
    
    def gettop(self):                       #get top of stack
        return self.__top
    
    
    
class express:                                      #expression class
    
    def __init__(self,ptr):
        
        self.__s = stack()                          #stack for analysis
        self.__pStr = ptr                           #input string
        self.__len = len(self.__pStr)               #length of input string
        
        
    def parse(self):                                #add items to stack
        
        for j in range(self.__len):                 #for each input character
            
            ch = self.__pStr[j]                     #get next character
            
            if ch >= '0' and ch<='9':               #if it's a digit,
                self.__s.push(ch)                   #save the character
                
                                                    #if it's operator
            elif ch == '+' or ch == '-' or ch == '*' or ch == '/':
                
                if self.__s.gettop() == 1:           #if it's first operator
                    self.__s.push(ch)                #put on stack
                    
                else:                                #not first operator
                    
                    lastval = self.__s.pop()         #get previous digit 
                    lastop = self.__s.pop()          #get previous operator
                    
                    
                    #if this is * or / AND last operator was + or -
                    if (ch=='*' or ch=='/') and (lastop == '+' or lastop == '-'):
                         
                        self.__s.push(lastop)           #restore last two pops
                        self.__s.push(lastval)
                        
                        
                    else:                               #in all other cases
                                                        #do last operation, and push result on stack
                        
                        if lastop == '+':
                            self.__s.push(str(int(self.__s.pop()) + int(lastval)))
                            
                        elif lastop == '-':
                            self.__s.push(str(int(self.__s.pop()) - int(lastval)))
                            
                        elif lastop == '*':
                            self.__s.push(str(int(self.__s.pop()) * int(lastval)))
                            
                        elif lastop == '/':
                            self.__s.push(str(int(int(self.__s.pop()) / int(lastval))))
                            
                        else:
                            print 'Unknown oper'
                            
                            
                    self.__s.push(ch)                    #put current operator on stack
                
                
            else:                                        #not a known character
                
                print 'Unkown input character'
            
            
            
    def solve(self):                                   #remove items from stack
        
        while self.__s.gettop() > 1:
            
            lastval = self.__s.pop()                   #get previous value
            
            a = self.__s.pop()                         #get previous operator
            
            
                                                       #do operation, push answer
            if a == '+':
                self.__s.push(str(int(self.__s.pop()) + int(lastval)))
                            
            elif a == '-':
                self.__s.push(str(int(self.__s.pop()) - int(lastval)))
                            
            elif a == '*':
                self.__s.push(str(int(self.__s.pop()) * int(lastval)))
                            
            elif a == '/':
                self.__s.push(str(int(int(self.__s.pop()) / int(lastval))))
                            
            else:
                print 'Unknown oper'
                
                
        return self.__s.pop()                #last item on stack is ans
    
    
    
    

print 'Enter an arithmetic expression'
print 'of the form 2+3*4/3-2'
print 'No number may have more than one digit.'
print 'Dont\'t use any spaces or parentheses.'    

while True:
    string = raw_input("Enter expression: ")              #input from user

    eptr = express(string)                                #make expression

    eptr.parse()                                          #parse it

    print '\nThe numerical value is: ',eptr.solve()       #solve it
    
    del eptr                                              #delete expression
    
    ans =  raw_input("\n\nDo another (Enter y or n)? ")
    
    if ans == 'n':
        break
Enter an arithmetic expression
of the form 2+3*4/3-2
No number may have more than one digit.
Dont't use any spaces or parentheses.
Enter expression: 2+3*4/3-2

The numerical value is:  4


Do another (Enter y or n)? y
Enter expression: 9+6/3

The numerical value is:  11


Do another (Enter y or n)? n
In [ ]: