Arrays  an array of 5 ints is filled with 3,2,4,1,7 int a[5] = {3,2,4,1,7}; // note squiggly brackets  an array of 3 floats is filled with 3.2,1.4,0;

Slides:



Advertisements
Similar presentations
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Advertisements

Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
11 Introduction to Object Oriented Programming (Continued) Cats II.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
February 11, 2005 More Pointers Dynamic Memory Allocation.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Memory Overview 4 major memory segments Key differences from Java
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
11 Introduction to Object Oriented Programming (Continued) Cats.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
 Memory from the heap  Dynamic memory allocation using the new operator  Build a dynamic linked list  Another way of traversing a linked list 
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
  A linked list is a collection of components called nodes  Every node (except the last one) contains the address of the next node  The address of.
1 Principles of Computer Science I Honors Section Note Set 3 CSE 1341.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
POINTERS AND MEMORY ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
Overview 4 major memory segments Key differences from Java stack
Linked lists.
Dynamic Memory CSCE 121 J. Michael Moore.
Dynamically Allocated Memory
Overview 4 major memory segments Key differences from Java stack
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Pointers & Functions.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Given the code to the left:
Pointers And Memory Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny.
What about multi-dimensional arrays?
Arrays an array of 5 ints is filled with 3,2,4,1,7
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Dynamic allocation (continued)
Pointers and References
Classes: Arrays group many objects of the same type (in order)
Linked lists.
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Arrays  an array of 5 ints is filled with 3,2,4,1,7 int a[5] = {3,2,4,1,7}; // note squiggly brackets  an array of 3 floats is filled with 3.2,1.4,0; float b[3] = {3.2,1.4};  makes an array of spaces for 7 ints; the array at 3 holds 24, rest holds nothing (if you print, will print their memory addresses ) int c[7]; c[3] = 24; cout << c[2] << endl; // prints something like 0x32ff3c, the memory address  Makes an array of 3 ints, holding 4,1,2 int d[] = {4,1,2};  Next: int d[]; d[0] = 4;  yeah, no. d[] is space for an address that will be where we hold the first int in the array, but so far no space has been set aside for the int, so there’s no address for the int.  Can we set aside space? Hold that thought…

Passing arrays into functions:  In terms of memory space, do we want to make a new, local copy of the array when we call a function?  To get the address of the array (aka a pointer to the array): int x[4] = {3,2,1,4}; cout << x << endl; //address of array, of where first value in array is cout << &x[0] << endl; //same value, address of first value in array

Arrays and Functions:  Note: no straightforward way of getting size of an array. We most likely want to pass in the length of the array along with a pointer to the array (aka the address of the array), e.g., int main() { int x[4]= {3,2,4,1}; double k = getAverage(&x[0],4); // gets the address of the first value in the array // Or double l = getAverage(x,4); // the address of the first value in the array cout << k << endl; } // main Function definition: double getAverage(int *arr, int size) // a pointer, a variable that holds an address {int sum = 0; for (int i = 0; i < size; i++) {sum += arr[i]; // now, in essence, the value at (the address of arr + i) } //for double avg = double(sum) / size; return avg; }//main Or double getAverage(int arr[], int size) { //holds the address of the first value in the array }

Returning an array int * createArray(int size) // what is returned??? { int r[size] = {3,2,4,1}; return r; // or return &r[0]; } //createArray int main() { int *a; a = createArray(4); for (int x = 0; x < 4; x++) { cout << a[x] << endl; } //for return 0; }//main

Dynamically allocated arrays  Means we make a pointer and then allocate the space for the values in the array  Maybe later, when we find out how many things will be in the array  Quick info: If the size of something is known when the program is compiled, then memory is set aside for it on the stack  int x = 3;  float y;  If the size of something is determined when the program is run, then there’s something called the heap (still in memory, but in a different place) that holds data. Stuff that goes on the heap is “dynamically allocated”.  The operator new sets aside space in the heap.  We often use pointers  If we allocate it, we should free it up

New and delete new int; // sets aside memory space on the heap for an int (but no variable points to it int *x; x = new int; // now x points to (holds the address of) space for an int on the heap *x = 34; // now the x points to 34; What if there’s not enough space on the heap? int *x; if( !(x = new int )) { cout << "Error: out of memory." <<endl; // checking to see if there’s space on the heap exit(1); } //if else { *x = 2; } //else And when you’re done with it… int *x; if( !(x = new int )) { cout << "Error: out of memory." <<endl; // checking to see if there’s space on the heap exit(1); } //if else { *x = 2; } //else delete x; //deallocates the space in memory

What about arrays? int *x = NULL; // Pointer initialized with null (default is undefined) cout << “Enter the number of numbers you want” << endl; int y; cin >> y; x = new int[y]; // Request memory on heap for space for 20 ints (sequentially) for (int k = 0; k < y; k++) { x[k] = k; } //for And now to free an array? delete [] x; //delete x; - why not? It compiles…

*x: X is a pointer. X holds the address of something else. Thus it must be made to point to: A: SOMETHING THAT EXISTS:  int y = 3;  int *x;  *x = y; // x now points to y – holds the address of y Or B: SOMETHING YOU CREATE (using new):  int *x;  x = new int[4]; // x now holds the memory location of space for 4 ints  x is a pointer, or address holder. Somehow, somewhere, the address must come to be before x can hold that address  And if something is new-ly created, it should be delete-d  AKA Garbage collection

What about multi-dimensional arrays? int **x = NULL; // Pointer initialized with null x = new int *[4]; // Allocate memory on heap for a 4x3 array for (int i = 0; i < 4; i++) { x[i] = new int[3]; } //for for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { x[i][j] = i+j; } //for for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { cout << x[i][j]; } //for cout << endl; } //for X

How about deleting? int **x = NULL; // Pointer initialized with null x = new int *[4]; // Allocate memory on heap for a 4x3 array for (int i = 0; i < 4; i++) { x[i] = new int[3]; } //for for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { x[i][j] = i+j; } //for Why can’t we just do this? delete [] x; // compiles just fine…

Deleting a multi-dimensional array int **x = NULL; // Pointer initialized with null x = new int *[4]; // Allocate memory on heap for a 4x3 array for (int i = 0; i < 4; i++) { x[i] = new int[3]; } //for for (int i = 0; i < 4; i++) { delete [] x[i]; } //for delete [] x;

Quick: int x = 3; int y = x; int *z = &x; cout << “x is “ << x <<endl; cout << “ y is “ << y << endl; cout << “ z is “ << *z << endl; x += 4; cout << “x is “ << x <<endl; cout << “ y is “ << y << endl; cout << “ z is “ << *z << endl; Can I do this? z = 3;

Structs  Arrays group many objects of the same type (in order)  Structs group objects of different types  Structs are similar to classes  Struct properties are, by default, public.  Structs often hold different types together (that logically belong together)  Example: struct StudentInfo { string fname; string lname; int id; StudentInfo next; }; //StudentInfo int main() { StudentInfo Sam; // could also say struct StudentInfo Sam; Sam.fname = "Sam"; Sam.lname = "Stone"; Sam.id = 3241; StudentInfo studarr[5]; studarr[1].fname = "Taylor"; cout << studarr[1].fname << endl; return 0; } //main

What do you think? struct StudentInfo { string fname; string lname; int id; }; //StudentInfo void changeStud(StudentInfo x) { x.fname = "Samantha"; } //changeStud int main() { StudentInfo Sam; Sam.fname = "Sammy"; Sam.lname = "Stone"; Sam.id = 3241; changeStud(Sam); cout << Sam.fname << endl; // what do you think? return 0; } //main

Call by Pointer struct StudentInfo { string fname; string lname; int id; }; //StudentInfo void changeStud(StudentInfo *x) { x->fname = "Sammy"; //new, means go to the name property in the address in x /* going to the address found in x and finding the field named fname */ } //changeStud int main() { StudentInfo Sam; Sam.fname = "Sam"; Sam.lname = "Stone"; Sam.id = 3241; changeStud(&Sam); cout << Sam.fname << endl; // what do you think? return 0; } //main

Dynamically allocated Struct struct StudentInfo { string fname; string lname; int id; }; //StudentInfo int main() { StudentInfo *c; c = new StudentInfo; c -> fname = "Charlie"; cout fname << endl; // go to the address found in c and find the fname field. }//main Works the same for class fields… fname lname id Charlie C

Dynamically allocated array of struct: struct StudentInfo { string fname; string lname; int id; }; //StudentInfo int main() { StudentInfo *b; b = new StudentInfo[3]; b[0].fname = "bob"; // why don’t we have to say b[0]->fname? // we are saying go to the address in b, and find the struct at 0 (the first struct). // all arrays act like pointers (point to the first ‘thing’ in the array) cout << b[0].fname << endl; }//main Same for arrays of class objects… fname lname id bob fname lname id fname lname id b 0 1 2

Dynamically allocated array in a struct: struct StudentInfo { string fname; string lname; int *grades; }; //StudentInfo int main() { StudentInfo *b; b = new StudentInfo[3]; b[0].fname = "bob"; cout << b[0].fname << endl; b[0].grades = new int[4]; b[0].grades[0] = 94; }//main fname lname grades bob fname lname grades fname lname grades b

Worse: Dynamically allocated field in a struct: struct StudentInfo { string fname; string lname; int *grades; }; //StudentInfo int main() { StudentInfo *b; b = new StudentInfo[3]; b[0].fname = "bob"; b[0].grades = new int; *(b[0].grades) = 94; // go to the address in b, find the 0 th struct, then // find the grades field, and go to the address in the grades field. cout << *(b[0].grades) << endl; }//main fname lname grades bob fname lname grades fname lname grades b

Again: Dynamically allocated field in a struct: struct StudentInfo { string fname; string lname; int *grades; }; //StudentInfo int main() { StudentInfo *b; b = new StudentInfo; b->fname = "bob"; b->grades = new int; *(b->grades) = 94; // go to the address in b, find the grades field, and // go to the address in the grades field. cout grades) << endl; }//main fname lname grades bob b 94

Struct with pointer to struct… struct LL { int data; LL *next; }; int main() { LL *first = new LL; first->data = 1; first->next = new LL; first->next->data = 2; first->next->next = new LL; first->next->next->data = 3; first->next->next->next = NULL; LL *lptr = first; while (lptr != NULL) { cout data << " "; lptr = lptr->next; } //while cout << endl; }//main NULL first Now we’re getting to the fun stuff… temporarily…

struct LL { int data; LL *next; }; void traverse (LL *x); int main() { LL *first; first = new LL; first->data = 1; first ->next = NULL; LL *second; second = new LL; second->data = 2; second ->next = NULL; first->next = second; LL *third; third = new LL; third->data = 3; third ->next = NULL; second->next = third; traverse (first); } void traverse(LL *ll) { LL *temp = ll; while (temp != NULL) { cout data <<endl; temp = temp->next; } cout << endl; } NULL first

class Rect { int length; // default – private – different from structs int width; int area; public: Rect() { // this is a constructor length = 3; width = 4; area = length * width; } //Constructor void setLen(int x) { // Setters: why do I need this? (do the same for width – why not area?) length = x; area = length * width; } //setLen int getLen() { //Getters (do the same for width return length; } //getLen int getArea() { return area; } //getArea }; //Rect int main() { Rect r(3,4); // constructor happens r.setLen(2); cout << r.getLen() << endl; cout << r.getArea() << endl; return 0; } //main Classes: Method 1 Closest to what you’ve seen with Java

Classes: method 2 class Rect { int length; int width; int area; public: Rect (int x, int y); void setLen(int x); int getLen(); int getArea(); }; //Rect header Rect::Rect(int x, int y) { length = x; width = y; area = length * width; } void Rect::setLen(int x) { //add setWidth length = x; area = length * width; } int Rect:: getLen() { // add getWidth return length; } int Rect::getArea() { return area; } int main() { Rect r(3,4); // constructor happens r.setLen(2); cout << r.getLen() << endl; cout << r.getArea() << endl; return 0; } //main

Classes: using header files: In header file (Rect.hpp) class Rect { int length; int width; int area; public: Rect (int x, int y); void setLen(int x); void setWid(int x); int getLen(); int getWid(); int getArea(); }; //Rect header In main file (MainProg.cpp) #include #include "Rect.hpp" using namespace std; int main() { Rect r(3,4); // constructor happens r.setLen(2); r.setWid(3); cout << r.getLen() << endl; cout << r.getArea() << endl; return 0; } //main In separate file (Rect.cpp) #include "Rect.hpp" Rect::Rect(int x, int y) { length = x; width = y; area = length * width; } void Rect::setLen(int x) { length = x; area = length * width; } void Rect::setWid(int x) { width = x; area = length * width; } int Rect:: getLen() { return length; } int Rect::getWid() { return width; } int Rect::getArea() { return area; }