Chapter 17 : Pointers with Multidimensional Array

Example: 1, Page No.:5.123

In [2]:
#Program to print the values and addres of the array elements.

arr=([[5,100],[10,200],[15,300],[20,400]])

for a in range(0,4):
    print "Address of %d array= %u"%(a,id(arr[a]))
    for b in range(0,2):
        print "Value =%d"%(arr[a][b])
Address of 0 array= 4336406328
Value =5
Value =100
Address of 1 array= 4336414944
Value =10
Value =200
Address of 2 array= 4336414800
Value =15
Value =300
Address of 3 array= 4366918504
Value =20
Value =400

Example: 2, Page No.: 5.125

In [8]:
#Program to print the value and address of the element using array of pointers

a=[0,1,2]
b=10
c=20
d=30
a[0]=b
a[1]=c
a[2]=d
for i in range(0,3):
    print "Address = %u"%id(a[i])
    print "Value = %d" % (a[i])
Address = 4298181184
Value = 10
Address = 4298180944
Value = 20
Address = 4298180704
Value = 30

Example: 3, Page No.: 5.126

In [23]:
#Program to sort a list of strings in alphabetical order using array of pointers.

a = []
n= input("Enter the number of strings: ")
print "Enter each string on a separate line below."
for i in range(0,n):
    a.append(0)
    
for i in range(0,n):
    a[i]=raw_input("String %d: " %(i+1))
for i in range(0,n):
    for j in range(i,n):
        if a[i]>a[j]:
            t = a[i]
            a[i] = a[j]
            a[j] = t
print "\nReordered List of Strings: "
for i in range(0,n):
    print "String %d: %s" %(i+1,a[i])
Enter the number of strings: 6
Enter each string on a separate line below.
String 1: venkat
String 2: ramesh
String 3: babu
String 4: muni
String 5: shankar
String 6: saravanan

Reordered List of Strings: 
String 1: babu
String 2: muni
String 3: ramesh
String 4: saravanan
String 5: shankar
String 6: venkat

Example: 4, Page No.: 5.128

In [27]:
#Program to count number of words

str=[]
ps=raw_input("Enter a string: ")
print len(ps.split()), "word(s) in the given string"
Enter a string: I am a student.
4 word(s) in the given string

Example: 5, Page No.: 5.129

In [34]:
#Program to demonstrate on strings and pointers

s1="abcd"
s2='efgh'

print "%s %16lu \n" % (s1,id(s1))
print "%s %16lu \n" % (s2,id(s2)) 

s1=s2
print "%s %16lu \n" % (s1,id(s1))
print "%s %16lu \n" % (s2,id(s2))
abcd       4363408224 

efgh       4363332704 

efgh       4363332704 

efgh       4363332704