1 / 21

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

allayna
Download Presentation

CS352-Week 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS352-Week 2

  2. Topics • Heap allocation • References • Pointers

  3. 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

  4. 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

  5. Function to add values What is the output generated by this code? //add.cc #include <iostream> using namespace std; int add(inti, int j){ return i+j; } intmain() { intm = 5, n =10; cout<<"inputs: “<< m <<“ “<<n<<“endl; cout<<"inputs: “<< add(m,n) <<“endl; } static_cast is used to convert x and y to integers via truncation inputs 5 10 outputs 15

  6. Program to swap values //swap1.cc #define <iostream> using namespace std; intmain() { intm = 5, n =10; cout<<"inputs: “<< m <<“ “<<n<<“endl; swap(m, n); cout<<"inputs: “<< m <<“ “<<n<<“endl; } void swap(inti, intj){ inttemp = i; i= j; j = temp; } No compile errors. Why doesn’t this work? inputs 5 10 outputs 5 10 We wish to change the parameters that are passed (m and n) This is called mutation or mutating the parameters

  7. Call by value Native types are passed to a function using call by value int m=5, n=10; swap(m,n) swap(inti, int j) m n 0101 1010 20 21 Values are copied to stack (special memory section to store function parms) special code to save place in calling function and get ready to execute function 1010 ij 0101 Thei = 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

  8. Call by value Native types are passed to a function using call by value int m=5, n=10; swap(&m,&n) swap(int * i, int * j) m n 0101 1010 20 21 Addresses are copied to stack special code to save place in calling function and get ready to execute function 20 i j 21 Must let function know that we passed addresses not values

  9. 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 10 outputs 10 5

  10. C++ style program to swap values //swap3.cc #define <iostream> using namespace std; intmain() { intm = 5, n =10; cout<<"inputs: “<< m <<“ “<<n<<“endl; swap(m, n); cout<<"inputs: “<< m <<“ “<<n<<“endl; } void swap(int &i, int &j){ inttemp = 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 The & lets the compiler know to use the addresses rather than the values inputs 5 10 outputs 10 5 References are also useful because they prevent the copying of the function parameters.

  11. Arrays pos variable is a pointer 1320 //Declares/Allocates 6 consecutive integers //init depends upon scope intpos[6]; //Declares/Allocates 6 consecutive integers and initializes them with given values intpos={0,2,4,6,8,10}; pos[0]=16; cout<<pos; //prints 1320 cout<<pos[0]; //prints 16 cout<<*pos; //print 16 *pos++; cout<<*pos; //prints 2 Variable designators are pointers that refer to the address of the lowest lot

  12. Arrays OUTPUT pointer to Array 1 0xffbff158 pos 0 int intArray1 is -4198016 pos 1 int intArray1 is 67896 pos 2 int intArray1 is -12775520 pos 3 int intArray1 is 0 pos 4 int intArray1 is 0 pos 5 int intArray1 is 0 pointer to Array 2 0xffbff140 value of iterator (ptr to Array 2) 0xffbff140 pos 0 int intArray2 is 2 iterator value 0 int intArray2 is 0xffbff140 pos 1 int intArray2 is 4 iterator value 1 int intArray2 is 0xffbff144 pos 2 int intArray2 is 6 iterator value 2 int intArray2 is 0xffbff148 pos 3 int intArray2 is 8 iterator value 3 int intArray2 is 0xffbff14c pos 4 int intArray2 is 10 iterator value 4 int intArray2 is 0xffbff150 pos 5 int intArray2 is 0 iterator value 5 int intArray2 is 0xffbff154 Print uninitialized array //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 (inti=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 (inti=0;i<6;i++){ cout <<"pos "<< i << " int intArray2 is "<< *iterator <<endl; cout <<"iterator value "<< i << " int intArray2 is "<< iterator++ <<endl; } } Can’t increment/change the declared array value You can create a 2nd pointer that points at the beginning of the array Pointer arithmetic (++,--,+,-) Iterates over array just as indexes can

  13. Array Allocation, Declaration, and Initialization //ADI array pointer and AD(I) array of 10 ints int array2[10]; //Arrays can only be allocated in global/local //scope is if the size is known int array1[]; //why not allocate the array? **Sometimes we do not know the size of array we will need

  14. 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

  15. Variable ADIWhere and how matters 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-nothing int * 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 (inti=0;i<count;i++) integerList[i]=rand(); cout<<“Number list of ”<<count<<endl; for (inti=0;i<count;i++) cout <<”Value at “<< i << ” is “<< integerList[i]<<endl; return 0; } count i int L2[4]; //reference ADI; array-ADI in data int* 2,4,6,8,9,10,…. L2 integerList 0,0,0,0

  16. 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

  17. Smart Car Vehicle Contain both static and dynamic state Attributes doorCount=2 isDriverDoorClosed=T Methods getDoorCount(){ return doorCount; } isDriverDoorClosed() { return isDriverDoorClosed; } openDriverDoor() { driverDoorIsClosed=F; } Accessor-return state; read only Mutator-changes state

  18. Class definition class Vehicle { public: getDoorCount(); isDriverDoorClosed(); openDriverDoor(); private: doorCount=2; isDriverDoorClosed=T; }

  19. 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 • BjarneStroustrup, Grady Booch • Object-Oriented Analysis and Design with Applications • Design patterns: Elements of Reusable Code

  20. 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

  21. 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

More Related