Structured Data. CIS 15 : Spring 2007

Similar documents
9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

Pointers, Dynamic Data, and Reference Types

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

a data type is Types

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

What is an algorithm?

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CMSC 202 Midterm Exam 1 Fall 2015

Lab # 02. Basic Elements of C++ _ Part1

Exam 3 Chapters 7 & 9

CS31 Discussion 1E Spring 17 : week 08

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Homework #3 CS2255 Fall 2012

Pointers. Variable Declaration. Chapter 10

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

IT 1033: Fundamentals of Programming Data types & variables

Linked List using a Sentinel

CS242 COMPUTER PROGRAMMING

Tokens, Expressions and Control Structures

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

05-01 Discussion Notes


Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Short Notes of CS201

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

CS201 - Introduction to Programming Glossary By

Objectives. In this chapter, you will:

Variables. Data Types.

C++ for Java Programmers

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

CS201- Introduction to Programming Current Quizzes

Programming, numerics and optimization

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CS2255 HOMEWORK #1 Fall 2012

CS2141 Software Development using C/C++ C++ Basics

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Input And Output of C++

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Name. CPTR246 Spring '17 (100 total points) Exam 2

Homework Assignment #1

Review Questions for Final Exam

Exercise: Inventing Language

Summary of basic C++-commands

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

The C++ Language. Arizona State University 1

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Assignment #1 (50 points; due 11:59 P.M.)

Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

CS 231 Data Structures and Algorithms, Fall 2016

CSC 1300 Exam 4 Comprehensive-ish and Structs

typedef int Array[10]; String name; Array ages;

Memory and Pointers written by Cathy Saxton

Recitation 3 Class and Objects

Memory and C++ Pointers

Integer Data Types. Data Type. Data Types. int, short int, long int

CS 103 Unit 11. Linked Lists. Mark Redekopp

CPSC 427: Object-Oriented Programming

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

C++ Programming: From Problem Analysis to Program Design, Third Edition

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Topic 2: C++ Programming fundamentals

COMP 202 Java in one week

Overloading Operators

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

Computer Science II Lecture 1 Introduction and Background

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Reviewing all Topics this term

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Variables and Functions. ROBOTC Software

Chapter 7. Additional Control Structures

Lectures 6/7 Pointers and Dynamic Arrays

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Pointers II. Class 31

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

CHAPTER 7 OBJECTS AND CLASSES

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Transcription:

Structured Data CIS 15 : Spring 2007

Functionalia HW4 Part A due this SUNDAY April 1st: 11:59pm Reminder: I do NOT accept LATE HOMEWORK. Today: Dynamic Memory Allocation Allocating Arrays Returning Pointers from Functions Structured Data

Const variables need Pointers to a Const const int SIZE = 3; const double payrates[size] = {12.11, 20.34, 34.32}; displaypayrates(payrates, SIZE); Prototype: void displaypayrates(const double *rates, int size); Not necessary. Why?

Const variables need Pointers to a Const const int SIZE = 3; const double payrates[size] = {12.11, 20.34, 34.32}; displaypayrates(payrates, SIZE); void displaypayrates(const double *rates, int size); Write the code to display the Pay Rates in Dollars ($) Using POINTERS (*) AND NOT ARRAYS ([])

Constant Pointers A pointer ITSELF can be a constant. int valuea = 29; int valueb = 35; int * const ptr = &valuea; ptr = &valueb; *ptr = valueb; // error: assignment of read-only variable 'ptr' // OK! ptr++; (*ptr)++; // error: increment of read-only variable 'ptr' // OK!

What is this? int value = 29; const int * const ptr = &value; cout << *ptr << endl; ptr++; (*ptr)++;

What is this? int value = 29; const int * const ptr = &value; A constant pointer to a constant variable. (Note that the variable itself can be a non-constant, but the const int protects it) ptr++; (*ptr)++; Error! Error!

int array[5] = {1,2,3,4,5}; Exercises //A if(array < &array[1]) cout << "True"; else cout << "False"; //C if(array!= &array[2]) cout << "True"; else cout << "False"; //B if(&array[4] < &array[1]) cout << "True"; else cout << "False"; //D if(array!= &array[0]) cout << "True"; else cout << "False";

int array[5] = {1,2,3,4,5}; Exercises //A if(array < &array[1]) cout << "True"; else cout << "False"; True //C if(array!= &array[2]) cout << "True"; else cout << "False"; True //B if(&array[4] < &array[1]) cout << "True"; else cout << "False"; False //D if(array!= &array[0]) cout << "True"; else cout << "False"; False

Exercises Write a function that takes a pointer to an integer as its input and converts it to a negative integer (only if it is positive, however)! Here is the prototype to help you get started: void makenegative(int *val); Write some code the demonstrates the use of this function.

Exercises void makenegative(int *val) { if(*val > 0) *val = -(*val); } Write some code the demonstrates the use of this function. int a = 1; int b = -1; makenegative(&a); makenegative(&b); cout << a << << b << endl;

Variables can be created and destroyed While a program is running, variables (and arrays of variables) can be created on the fly through dynamic memory allocation. The program asks the computer for an unused chunk of memory with the size of the variable requested. The computer returns the starting address of the chunk of memory. This starting address is stored in a pointer. Use the new operator along with the type of the variable you want. int * ptr; ptr = new int; *ptr = 25; cout << *ptr; cin >> *ptr; (*ptr)++;

Dynamically Allocating Arrays Dynamically Allocating Arrays is the more common use of the new operator: int * ptr; ptr = new int[100]; // creates a 100 integer sized array Use ptr the same way one would use an integer array name. for(int i = 0; i < 100; i++) ptr[i] = 1;

Dynamically Allocating Arrays Not limited to only using integers. char * cptr; cptr = new char[27]; // creates a 27 character sized array What is stored in the cptr array? for(int i = 0; i < 26; i++) cptr[i] = a + i; cptr[26] = \0 ;

Dynamically Allocating Arrays Not limited to only using integers. char * cptr; cptr = new char[27]; // creates a 27 character sized array What is stored in the cptr array? for(int i = 0; i < 26; i++) cptr[i] = a + i; cptr[26] = \0 ; abcdefghijklmnopqrstuvwxyz NULL byte at the end

Memory is finite int * wholelottamemory = new int[1000000000000000000000000]; What happens when the computer runs out of memory? 1. Throws an Exception (Error Handling in C++) 2. Returns memory address 0 (also known as NULL) int * ptr = new int[100]; if(ptr == NULL) { cout << Error allocating memory\n ; return; }

What is created must be deleted! When your program is finished using dynamically allocated memory, it must free the memory for future use. int * ptr; ptr = new int; *ptr = 5; Free the memory by using the delete operator *ptr = *ptr + 2;... delete ptr;

Pointers are able to be resued delete does not remove the pointer. It only FREES the memory that it points to. int * ptr; ptr = new int; *ptr = 5; *ptr = *ptr + 2; delete ptr; ptr = new int; *ptr = 3; delete ptr; Always free the memory that you dynamically allocate. C++ does not do garbage collection

Deleting Arrays To delete dynamically allocated arrays, need to add the [] symbol. char * cptr; cptr = new char[27]; // creates a 27 character sized array... delete [] cptr; Not deleting dynamically allocated memory creates memory leaks. (And results in sluggish and failing programs).

Always check for NULL NULL points to memory address 0. Not a usable address. Operating system data is stored in the lower memory address space. Always check if a pointer is pointing to NULL. When a pointer is not being used any more. Set it to NULL. char * cptr; cptr = new char[27]; // creates a 27 character sized array... delete [] cptr; cptr = NULL;

What s wrong? Note: Functions can return pointers (Take a look at all C String Functions). char * getname() { char name[81]; cout << Enter your name: ; cin.getline(name, 81); return name; }

What s wrong? Note: Functions can return pointers (Take a look at all C String Functions). name is a local variable to the function. char * getname() { char name[81]; Exists only within the scope of the function. cout << Enter your name: ; cin.getline(name, 81); return name; }

Dynamically Allocate the Memory Functions themselves can dynamically allocate memory, return a pointer to the memory, and the memory sticks around beyond the scope of the function. char * getname() { char * name; name = new char[81]; cout << Enter your name: ; cin.getline(name, 81); return name; } char * yourname = getname(); cout << yourname << endl; delete [] yourname;

Dynamically Allocate the Memory This is how MEMORY LEAKS can happen. When you lose track of memory and forget to free it. char * getname() { char * name; name = new char[81]; cout << Enter your name: ; cin.getline(name, 81); return name; } char * yourname = getname(); cout << yourname << endl; delete [] yourname;

Exercises 1. Assume that ip is a pointer to an int. Write a statement that will dynamically allocate an integer variable and store its address in ip. Write a statement that will free the memory allocated to ip. 2. Assume ip is a pointer to an int. Then, write a statement that will dynamically allocate an array of 500 integers and store its address in ip. Write a statement that will free the memory allocated in the statement you just wrote.

Exercises 1. Assume that ip is a pointer to an int. Write a statement that will dynamically allocate an integer variable and store its address in ip. Write a statement that will free the memory allocated to ip. int * ip; ip = new int; *ip = 255; delete ip; 2. Assume ip is a pointer to an int. Then, write a statement that will dynamically allocate an array of 500 integers and store its address in ip. Write a statement that will free the memory allocated in the statement you just wrote.

Exercises 1. Assume that ip is a pointer to an int. Write a statement that will dynamically allocate an integer variable and store its address in ip. Write a statement that will free the memory allocated to ip. 2. Assume ip is a pointer to an int. Then, write a statement that will dynamically allocate an array of 500 integers and store its address in ip. Write a statement that will free the memory allocated in the statement you just wrote. int * ip; ip = new int[500]; for(int i = 0; i < 500; i++) *(ip + i) = 255; delete [] ip;

Primitive Data Types So far (with the exception of learning a little bit of Classes in 1.5), the data types you re accustomed to are: bool int unsigned long int char long int float unsigned char unsigned short int double short int unsigned int long double

Structured Data To provide a level of Abstraction, C++ allows you to group several variables together into a single item known as structure. What is Abstraction? A struct is similar to a class, but more simple, in that it abstracts only data, and not functions. An array allows one to package variables and data together, but what is it s limitation?

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { int hour; int minutes; int seconds; }; Time now;

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { int hour; int minutes; int seconds; Keyword struct to indicate that what follows is a struct. }; Time now;

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { }; int hour; int minutes; int seconds; The tag (i.e. name of the new structured data-type you are defining). Time now;

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { }; int hour; int minutes; int seconds; It is customary to always Capitalize the first letter of the name of a structure. Time now;

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { int hour; int minutes; int seconds; The member data types are contained in curly braces (just like functions) }; Time now;

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { int hour; int minutes; }; int seconds; Time now; NOTE! There is a semicolon at the end of the struct (unlike functions)

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { }; int hour; int minutes; int seconds; Variables are declared like in any function. Time now;

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { int hour; int minutes; int seconds; }; Time now; Your structure can be declared now as any other variable.

Anatomy of a struct Here is a structure (called Time) that contains 3 integers (hour, minutes, and seconds). struct Time { int hour; This is the definition. (Only one). }; int minutes; int seconds; This is the instantiation. (Can be many). Time now; Time later;

Definition of structs Typically struct s are defined outside of any functions, and at the top of the program (i.e. near the prototypes). Why? struct Date { int day, month, year; char longname[255]; }; int main() { Date current; }

Definition of structs Note the mixture of data-types, and using one line for the integers. struct Date { int day, month, year; char longname[255]; }; int main() { Date current; }

Accessing the members of a struct You can access the members of a struct variable through dot-notation. struct Date { int day, month, year; char longname[255]; }; int main() { Date current; current.day = 26; current.month = 3; current.year = 2007; strcpy(current.longname, Bangladesh - Independence Day ); }

Accessing the members of a struct Why won t this work? struct Date { int day, month, year; char longname[255]; }; int main() { Date current; cout << Enter the current date: ; cin >> current; cout << current << endl; }