Download - CS352-Week 2
CS352-Week 2
Topics
• Heap allocation• References • Pointers
Previous knowledge
• vi/vim information http://troll.cs.ua.edu/cs150/
• Concept of an array allocating the data in a sequence that is all the same type
• Functions - http://troll.cs.ua.edu/cs150/book/index_9.html
– Understanding of passing read only parameters to a function
– Understanding of returning a value from a function
– Denote type of variable in formal parameter list
Objectives
• Dynamically allocate an array of any native type• Understand how/where local variables, global variables
and dynamically allocated variables are stored• Multiple ways to refer to an array member and iterate
over an array• Understanding of pass by reference vs pass by value• Motivation for using references instead of pointers• Motivation for using references to reduce processing
Function to add values//add.cc#include <iostream>using namespace std;int add(int i, int j){
return i+j;}
int main() {int m = 5, n =10;
cout<<"inputs: “<< m <<“ “<<n<<“endl;cout<<"inputs: “<< add(m,n) <<“endl;
}
What is the output generated by this code?
static_cast is used toconvert x and y to integers via truncation
inputs 5 10outputs 15
Program to swap values//swap1.cc#define <iostream>using namespace std;int main() {
int m = 5, n =10;
cout<<"inputs: “<< m <<“ “<<n<<“endl;swap(m, n);cout<<"inputs: “<< m <<“ “<<n<<“endl;
}void swap(int i, int j){
int temp = i;i = j;j = temp;
}We wish to change the parameters that are passed (m and n)This is called mutation or mutating the parameters
inputs 5 10outputs 5 10
No compile errors.Why doesn’t this work?
Call by valueNative types are passed to a function using call by value
int m=5, n=10;swap(m,n)
swap(int i, int j)
0101 1010
m n
0101
1010
Values are copied to stack (special memory section to store function parms)i
j
special code to save place in calling function and get ready to execute function
The i = j statement only affects the memory that holds the copy, not the original
If we send the address of the variables in memory, we can change the original values
20 21
Call by valueNative types are passed to a function using call by value
int m=5, n=10;swap(&m,&n)
swap(int * i, int * j)
0101 1010
m n
21
20
Addresses are copied to stack
i j
special code to save place in calling function and get ready to execute function
20 21
Must let function know that we passed addresses not values
C style program to swap values//swap2.cc#define <iostream>using namespace std;int main() {
int m = 5, n =10;
cout<<"inputs: “<< m <<“ “<<n<<“endl;swap(&m, &n);cout<<"inputs: “<< m <<“ “<<n<<“endl;
}void swap(int * i, int * j){
int temp = *i; //moves contents in i to local variable temp*i = *j; //moves contents in j to address pointed to by i*j = temp; //moves value temp to address pointed to by j
}
This function is a mutator; it changes the original value
inputs 5 10outputs 10 5
C++ style program to swap values//swap3.cc#define <iostream>using namespace std;int main() {
int m = 5, n =10;
cout<<"inputs: “<< m <<“ “<<n<<“endl;swap(m, n);cout<<"inputs: “<< m <<“ “<<n<<“endl;
}void swap(int &i, int &j){
int temp = i; //moves contents in i to local variable tempi = j; //moves contents in j to address pointed to by ij = temp; //moves value temp to address pointed to by j
}
This function is a mutator; it changes the original valueThe & lets the compiler know to use the addresses rather than the values
inputs 5 10outputs 10 5
References are also useful because they prevent the copying of the function parameters.
Arrays
Variable designators are pointers that refer to the address of the lowest lot
//Declares/Allocates 6 consecutive integers //init depends upon scope
int pos[6];
//Declares/Allocates 6 consecutive integers and initializes them with given values
int pos={0,2,4,6,8,10};
pos[0]=16;
cout<<pos; //prints 1320cout<<pos[0]; //prints 16cout<<*pos; //print 16*pos++;cout<<*pos; //prints 2
pos variable is a pointer 1320
Arrays//arrays1.cc#include <iostream>using namespace std;
int main() { int intArray1[6]; int intArray2[]={2,4,6,8,10};
cout<<"pointer to Array 1 "<<intArray1<<endl;
for (int i=0;i<6;i++) cout <<"pos "<< i << " int intArray1 is "<< intArray1[i] <<endl;
cout<<endl; cout<<"pointer to Array 2 "<<intArray2<<endl<<endl;
//cout<<"Print iterated intArray2 pointer "<<--intArray2; //intArray2++;
int *iterator = intArray2; cout<<"value of iterator (ptr to Array 2) "<<iterator<<endl;
for (int i=0;i<6;i++){ cout <<"pos "<< i << " int intArray2 is "<< *iterator <<endl; cout <<"iterator value "<< i << " int intArray2 is "<< iterator++ <<endl; }}
OUTPUTpointer to Array 1 0xffbff158pos 0 int intArray1 is -4198016pos 1 int intArray1 is 67896pos 2 int intArray1 is -12775520pos 3 int intArray1 is 0pos 4 int intArray1 is 0pos 5 int intArray1 is 0
pointer to Array 2 0xffbff140
value of iterator (ptr to Array 2) 0xffbff140pos 0 int intArray2 is 2iterator value 0 int intArray2 is 0xffbff140pos 1 int intArray2 is 4iterator value 1 int intArray2 is 0xffbff144pos 2 int intArray2 is 6iterator value 2 int intArray2 is 0xffbff148pos 3 int intArray2 is 8iterator value 3 int intArray2 is 0xffbff14cpos 4 int intArray2 is 10iterator value 4 int intArray2 is 0xffbff150pos 5 int intArray2 is 0iterator value 5 int intArray2 is 0xffbff154
Print uninitialized array
Can’t increment/change the declared array valueYou can create a 2nd pointer that points at the beginning of the array
Pointer arithmetic (++,--,+,-)Iterates over array just as indexes can
Array Allocation, Declaration, and Initialization
//ADI array pointer and AD(I) array of 10 intsint array2[10];
//Arrays can only be allocated in global/local //scope is if the size is knownint array1[]; //why not allocate the array?
**Sometimes we do not know the size of array we will need
Dynamic allocation
• Many array sizes cannot be anticipated at compile time• Unknown array sizes have to be allocated at runtime• Space is allocated from heap (free store) which is
separate from the storage for other variables• Allocated space can be used globally *if* there is a
global pointer to it• Allocated space with a local pointer will cause the
pointer to be deallocated when it is out of scope *but* the space it pointed to still exists, called memory leak
• Once allocated, the space stays allocated until it is explicitly freed
Variable ADIWhere and how matters
integerList
counti
2,4,6,8,9,10,….
0,0,0,0
L2
int L2[4]; //reference ADI; array-ADI in data
You writing a program where you will generate a random number of integers and store them in an array
//dynamic1.cc#include <iostream>#include <ctime>#include <cstdlib>using namespace std;//reference-ADI; array-nothingint * integerList; //don’t know the random number of integers; can’t use []
int main() {srand(time(NULL));int count=rand()%10;
integerList = new int[count]; //dynamic allocation of space-”operator new”
for (int i=0;i<count;i++) integerList[i]=rand();
cout<<“Number list of ”<<count<<endl;for (int i=0;i<count;i++) cout <<”Value at “<< i << ” is “<< integerList[i]<<endl;return 0;
}
int *
Object-oriented Programming
• Data and functions are linked together• Attributes are the data fields in a class• Methods can be functions that act on the data
fields• Methods can be functions that return data state
to the caller• Classes are a type definition – No memory is allocated in a class definition
• Classes usually follow natural relationships and actions
Smart Car
Vehicle
AttributesdoorCount=2isDriverDoorClosed=T MethodsgetDoorCount(){
return doorCount;}isDriverDoorClosed() {
return isDriverDoorClosed;}openDriverDoor() {
driverDoorIsClosed=F;}
Contain both static
and dynamic state
Accessor-return state;read only
Mutator-changes state
Class definition
class Vehicle {
public:getDoorCount();
isDriverDoorClosed();openDriverDoor();
private:doorCount=2;
isDriverDoorClosed=T;}
Upcoming preparation• Class definitions• class scope• classes vs object• declaration, allocation and initialization• constructors and destructors
I will talk about syntax and semantics, not object oriented analysis and design (determining appropriate classes, methods, attributes and interactions)
Resources• Bjarne Stroustrup, Grady Booch• Object-Oriented Analysis and Design with Applications• Design patterns: Elements of Reusable Code
Recap
• Using references to allow functions to mutate values
• Reference types contain native types and other reference types
• Array declaration, allocation and initialization• Array variable holds address of first element• Dynamic array allocation of native type arrays• Pointer arithmetic
• I will not be here (either Dr Hong or a graduate student will be here)
• Thursday will be an in class assignment• 3 programs to be due at the end of class• Review the techniques and concepts so that
you can complete the assignment in 50 minutes