CSC 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.

Slides:



Advertisements
Similar presentations
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Advertisements

CSC 213 – Large Scale Programming. Today’s Goals  Consider what new does & how Java works  What are traditional means of managing memory?  Why did.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
Chapter 10.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
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 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Programming Pointers. COMP104 Lecture 32 / Slide 2 Pointers l Pointers are objects whose values are the locations of other objects l Pointers are memory.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSC 107 – Programming For Science. Today’s Goal  Learn how pointers really used with arrays  Exploit the similarity between pointers & arrays  Take.
CSC 107 – Programming For Science. Today’s Goal  Learn C functions to input and output data  Using printf to print out variables and strings  Read.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSC 107 – Programming For Science. Today’s Goal ALL  Understand why ALL I/O is file I/O  Common bugs to avoid when coding with files in C++  Get a.
CSC 107 – Programming For Science. Today’s Goal  Learn relationship between pointers & arrays  How and why they both are similar  Take advantage of.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
CSC 107 – Programming For Science. Today’s Goal Variables  Variable  Variable name location to store data  Only for humans; 0 x 7E8A2410 harder to.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CSC 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.
CSC 213 – Large Scale Programming. Today’s Goals  Consider what new does & how Java works  What are traditional means of managing memory?  Why did.
CSC 107 – Programming For Science. Today’s Goal  Learn how pointers really used with arrays  Exploit the similarity between pointers & arrays  Take.
CSC 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Dynamic memory allocation and Pointers Lecture 4.
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 Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CSC 107 – Programming For Science. Today’s Goal  Become familiar with simple arrays  Declaring an array variable  Assigning data to array entries 
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CSC 107 – Programming For Science. Today’s Goal  Better understand arrays and how they work  Using array variable & its entries  When calling function,
Copyright © – Curt Hill Pointers A Light Introduction.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
CSC 107 – Programming For Science. Today’s Goal  Learn what structures are & how they are used  Why we need & why would use a structure  What fields.
CSC 107 – Programming For Science. Science Means Solving Problems  Physics – How does an atom work?
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
CSC 213 – Large Scale Programming. Explicit Memory Management  Traditional form of memory management  Used a lot, but fallen out of favor  malloc /
PHY 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.
Variables and memory addresses
CSC 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.
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.
CSC 107 – Programming For Science. Today’s Goal  Discover best uses of structures in a program  How we can mix pointers inside structures  Assigning.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Dynamic Storage Allocation
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
CMSC 341 Prof. Michael Neary
Chapter 15 Pointers, Dynamic Data, and Reference Types
CS 2308 Exam I Review.
Presentation transcript:

CSC 107 – Programming For Science

Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How to declare array if size varies with each run  Using (& fixing problems) with new & delete  All doing great, but pointers still hard

Arrays vs. Pointers Arrays = YamsPointers = Sweet Potatoes  Makes space at declaration  Variable value is address  Use [] to access entries  Can also access using *  Can be assigned a pointer  Needs target to be useful  Variable value is address  Use * to access target  Can also access using []  Can be assigned array Often use pointers & arrays interchangeably

Use Like ArrayUse Like Pointer Arrays + Pointers = char array[100]; char * ptr = array; *array = ‘E’; *(ptr + 1) = ‘q’; *(ptr + 2) = ‘u’; *(array + 3) = ‘a’; *(ptr + 4) = ‘l’; *(array + 5) = ‘\0’; char array[100]; char * ptr = array; array[0] = ‘E’; ptr[1] = ‘q’; ptr[2] = ‘u’; array[3] = ‘a’; ptr[4] = ‘l’; array[5] = ‘\0’;

Pointers Can Be NULL

Starting a New Company  Developing software for your new company  Website selling engineering gear of all possible types  Plans to grow site to offer consulting & other services  Being as big as Amazon.com is your eventual goal  But, for the moment, your company is very small

Developing the Software  Want to write code that scales with company  Read inventory from file to make updates easy  By writing software in C++, can port to new machines  No hard limits (if possible) since guesses will be wrong

First Attempt At Writing Code  Use 2 arrays: one for names and one for costs  Work in parallel, so item data at same index in arrays  Number of items 1 st line of file to use declaring arrays  Know that in the future may not want files  Databases can be faster, but also more expensive  Read from files using function so easy to change later  Code is simple & easy  Code is simple & easy; what could go wrong?

First Attempt At Writing Code  Use 2 arrays: one for names and one for costs  Work in parallel, so item data at same index in arrays  Number of items 1 st line of file to use declaring arrays  Know that in the future may not want files  Databases can be faster, but also more expensive  Read from files using function so easy to change later  Code is simple & easy  Code is simple & easy; what could go wrong?

First Attempt At Writing Code  Code is simple & easy  Code is simple & easy; what could go wrong?

First Try At Code double[] readCosts(int & nItems) { // Open the file ifstream fIn(“moolah.txt”); // Read in the number of items & create the array fIn >> nItems; double costs[nItems]; // Now read the cost of each item from the file for (int i = 0; i > costs[i]; } // And return the array… return costs; }

Compile In MS Visual C++... double[] readCosts(int & nItems) { // Open the file ifstream fIn(“moolah.txt”); // Read in the number of items & create the array fIn >> nItems; double costs[nItems]; // Now read the cost of each item from the file for (int i = 0; i > costs[i]; } // And return the array… return costs; }

Compile In MS Visual C++... double[] readCosts(int & nItems) { // Open the file ifstream fIn(“moolah.txt”); // Read in the number of items & create the array fIn >> nItems; double costs[nItems]; // Now read the cost of each item from the file for (int i = 0; i > costs[i]; } // And return the array… return costs; }

Move to Eclipse + Mac OS double[] readCosts(int & nItems) { // Open the file ifstream fIn(“moolah.txt”); // Read in the number of items & create the array fIn >> nItems; double costs[nItems]; // Now read the cost of each item from the file for (int i = 0; i > costs[i]; } // And return the array… return costs; }

Compiles on Eclipse + Mac OS… double[] readCosts(int & nItems) { // Open the file ifstream fIn(“moolah.txt”); // Read in the number of items & create the array fIn >> nItems; double costs[nItems]; // Now read the cost of each item from the file for (int i = 0; i > costs[i]; } // And return the array… return costs; }

…& Crashes on Eclipse + Mac OS  Program behaves oddly without clear reasons  During program value of variables just change  Prices go up and down for no clear reason  At some bizarre time, program eventually crashes

…& Crashes on Eclipse + Mac OS  Program behaves oddly without clear reasons  During program value of variables just change  Prices go up and down for no clear reason  At some bizarre time, program eventually crashes

How To Write Buggy Programs  Unsafe to return  Unsafe to return array declared in function  Know how we draw boxes when we call function  Cross out box at end of that call to the function boxes really exist  Guess what? Those boxes really exist in memory  Within box are declared arrays’ memory locations!  Array uses the same address as other things  Odd behavior results as overwrite each other’s values  Memory shared with important data 

How To Write Buggy Programs  Unsafe to return  Unsafe to return array declared in function  Know how we draw boxes when we call function  Cross out box at end of that call to the function boxes really exist  Guess what? Those boxes really exist in memory  Within box are declared arrays’ memory locations!  Array uses the same address as other things  Odd behavior results as overwrite each other’s values  Memory shared with important data 

What To Do?  Do not want to have to declare array in main  Lots of rewrites needed if we do file I/O in main  Do not have money for huge array would need later  Cannot declare in function without risk of crash  How to make long-lived or variable-length arrays?

Dynamic Storage Allocation!  Way of allocating arrays in own memory space  No limits on space – array can be any (integer) size  Type must match variable, but no new restrictions  Memory reserved until explicitly returned to system  Array entries initialized to 0 when array allocated  Once it is allocated, use like normal array  Cannot tell difference given two valid arrays  Passing as parameter or returning from function okay

Dynamic Storage Allocation new new new new new int * ptr = new int[100]; char * cstring; double * ddd; int * arr; const int FOUR = 5; int val; cin >> val; cstring = new char[10]; ddd = new double [FOUR – 1 + 2]; arr = new int[val]; arr[2] = 23; long * pirate = new int[arr[2]];

All Done Now

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); Main Memory (RAM)

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); Main Memory (RAM) x

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; Main Memory (RAM) x

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; Main Memory (RAM) x ptr

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; delete [] x; Main Memory (RAM) x ptr

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; delete [] x; Main Memory (RAM) x ptr

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; delete [] x; // But I’m not dead yet! Main Memory (RAM) ptr

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; delete [] x; // But I’m not dead yet! char *y = new char[6]; strcpy(y, "sad"); cout << ptr << endl; // oops… Main Memory (RAM) y ptr 

Dangling Pointers char *x = new char[6]; strcpy(x, "happy"); char *ptr = x; delete [] x; // But I’m not dead yet! char *y = new char[6]; strcpy(y, "sad"); cout << ptr << endl; // oops…  Hard-to-find bugs created throughout code

Not Always A Laughing Matter

Your Turn  Get into your groups and try this assignment

For Next Lecture  Review of pointers in  What questions do you have about how they work?  Are you ready to use & trace them in programs?  Create and delete pointers during program running?  Angel has Weekly Assignment #11 available