pScore = 0 #declare and initialize a pointer
score = 1000 #assign pointer pScore address of variable score
pScore = score;
print "Assigning &score to pScore\n";
print "&score is: " , id(score) # address of score variable
print "pScore is: " , pScore # address stored in pointer
print "score is: " , score
print "pScore is: " , pScore # value pointed to by pointer
print "Adding 500 to score";
score += 500;
print "score is: " , score
print "*pScore is: " , pScore
print "Adding 500 to *pScore\n";
pScore += 500;
print "score is: " , score
print "*pScore is: " , pScore
print "Assigning &newScore to pScore\n";
newScore = 5000;
pScore = newScore;
print "&newScore is: " , id(newScore)
print "pScore is: " , pScore
print "newScore is: " , newScore
print "*pScore is: " , pScore
print "Assigning &str to pStr\n";
str = "score";
pStr = str;
print "str is: " , str
print "*pStr is: " , pStr
print "(*pStr).size() is: " , len(pStr)
print "pStr->size() is: " , len(pStr)
def badSwap(x,y):
x,y = y,x
def goodSwap(x,y):
x[0],y[0] = y[0],x[0]
myScore = [150]
yourScore = [1000]
print "Original values";
print "myScore: " , myScore[0]
print "yourScore: " , yourScore[0]
print "Calling badSwap()";
badSwap(myScore[0], yourScore[0]);
print "myScore: " , myScore[0]
print "yourScore: " , yourScore[0]
print "Calling goodSwap()\n";
goodSwap(myScore,yourScore);
print "myScore: " , myScore[0]
print "yourScore: " , yourScore[0]
def ptrToElement(pVec, i):
return pVec[i]
inventory = []
inventory.append("sword");
inventory.append("armor");
inventory.append("shield");
#displays string object that the returned pointer points to
print "Sending the objected pointed to by returned pointer:";
print ptrToElement(inventory, 0)
# assigns one pointer to another - - inexpensive assignment
print "Assigning the returned pointer to another pointer.";
pStr = ptrToElement(inventory, 1);
print "Sending the object pointed to by new pointer to cout:";
print pStr
#copies a string object - - expensive assignment
print "Assigning object pointed by pointer to a string object.\n";
s = (ptrToElement(inventory, 2));
print "Sending the new string object to cout:";
print s
#altering the string object through a returned pointer
print "Altering an object through a returned pointer.";
pStr = "Healing Potion";
inventory[1] = pStr
print "Sending the altered object to cout:\n";
print inventory[1]
def increase(array,NUM_ELEMENTS):
for i in range(NUM_ELEMENTS):
array[i] += 500;
def display( array, NUM_ELEMENTS):
for i in range(NUM_ELEMENTS):
print array[i]
print "Creating an array of high scores.\n\n";
NUM_SCORES = 3;
highScores = [5000, 3500, 2700]
print "Displaying scores using array name as a constant pointer.";
print highScores[0]
print highScores[1]
print highScores[2]
print "Increasing scores by passing array as a constant pointer.";
increase(highScores, NUM_SCORES)
print "Displaying scores by passing array as a constant pointer to a constant.";
display(highScores, NUM_SCORES);