Review: arrays, pointers, structures (Chapter 1) Data Types. Review: Arrays. Data Types (C/C++) Data Type: CS 3358 Summer I 2012.

Similar documents
Answers to Review Questions Chapter 7

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

C++ INTERVIEW QUESTIONS

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

An Incomplete C++ Primer. University of Wyoming MA 5310

Data Structures using OOP C++ Lecture 1

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

El Dorado Union High School District Educational Services

Object Oriented Software Design II

The C Programming Language course syllabus associate level

5 Arrays and Pointers

Sources: On the Web: Slides will be available on:

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Object Oriented Software Design II

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Cours de C++ Utilisations des conteneurs

Introduction to Data Structures

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Chapter One Introduction to Programming

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Programming Block Tutorial C/C++

Cpt S 223. School of EECS, WSU

Passing 1D arrays to functions.

Semantic Analysis: Types and Type Checking

Moving from CS 61A Scheme to CS 61B Java

Comp151. Definitions & Declarations

C++ Programming Language

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Basics of C++ and object orientation in OpenFOAM

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C++ Language Tutorial

Chapter 13 Storage classes

C++FA 5.1 PRACTICE MID-TERM EXAM

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Introduction to Java

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Stacks. Linear data structures

Sequences in the C++ STL

Beyond the Mouse A Short Course on Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

VB.NET Programming Fundamentals

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

1 Abstract Data Types Information Hiding

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Fondamenti di C++ - Cay Horstmann 1

Chapter 07: Instruction Level Parallelism VLIW, Vector, Array and Multithreaded Processors. Lesson 05: Array Processors

C++FA 3.1 OPTIMIZING C++

SmartArrays and Java Frequently Asked Questions

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Specific Simple Network Management Tools

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Here are some examples of combining elements and the operations used:

Data Structures Using C++ 2E. Chapter 5 Linked Lists

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Matrix Multiplication

Chapter 5. Selection 5-1

CSI33 Data Structures

C Strings and Pointers

Lecture 5: Java Fundamentals III

Linked Lists: Implementation Sequences in the C++ STL

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Variable Base Interface

Database Programming with PL/SQL: Learning Objectives

Class 16: Function Parameters and Polymorphism

Object Oriented Software Design II

Chapter 5 Functions. Introducing Functions

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

Tutorial on C Language Programming

C++ Support for Abstract Data Types

13 Classes & Objects with Constructors/Destructors

Moving from C++ to VBA

AP Computer Science Java Subset

Glossary of Object Oriented Terms

Arrays in Java. Working with Arrays

arrays C Programming Language - Arrays

Java from a C perspective. Plan

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Appendix K Introduction to Microsoft Visual C++ 6.0

Introduction to Computer Graphics with WebGL

Oracle Database: SQL and PL/SQL Fundamentals

COMPUTER SCIENCE 1999 (Delhi Board)

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Chapter 2: Elements of Java

C++ Input/Output: Streams

Transcription:

Review: arrays, pointers, structures (Chapter 1) Data Types Data Type: CS 3358 Summer I 2012 Jill Seaman set of values set of operations over those values example: Integer whole numbers, -32768 to 32767 +, -, *, /, %, ==,!=, <, >, <=, >=,... Which operation is not valid for float? 1 Data Types (C/C++) Review: Arrays Scalar (or Basic) Data Types (atomic values) Arithmetic types Integers short, int, long char, bool Floating points float, double, long double Composite (or Aggregate) Types: Arrays: ordered sequence of values of the same type Structures: named components of various types 3 An array contains multiple values of the same type. values are stored consecutively in memory. An array definition in C++: int numbers[5]; Array indices (subscripts) are zero-based numbers[0]... numbers[4] the subscript can be ANY integer expression: numbers[2] numbers[i] numbers[(i+2)/2] What operations can be performed over (entire) arrays? 4

First-Class vs Second-Class objects first-class objects can be manipulated in the usual ways without special cases and exceptions - copy (=, assignment) - comparison (==, <,...) - input/output (<<, >>) second-class objects can be manipulated only in restricted ways, may have to define operations yourself - Usually primitive (built-in) data types 5 First-Class vs Second-Class objects: Strings second-class object: C-String (char array) - strcpy - strlen - strcat - strcmp first-class object: string class (standard library) - = - size() member function - ==, <,... - + Special functions The usual operators 6 First-Class vs Second-Class objects: arrays second-class object: primitive array - = does not copy elements - length undefined - ==, <,... do not perform as expected first-class object: vector class (standard template library) - = - size() member function - ==, <,... usual operations are not defined The usual operators 7 vector and string Included in standard (template) library class definitions used for first class objects The definitions provide an interface that hides the implementation from the programmer. Programmer does not need to understand the implementation to use the types. Vector: like an array, can contain elements of any single given type. 8

Using vector Using vector Include file #include <vector> To define a vector give a name, element type, and optional size (default is 0): vector<int> a(3); // 3 int elements Can use [ ] to access the elements (0-based): a[3] = 12; Use the size member function to get the size: cout << a.size() << endl; //outputs 3 9 Use resize() to change the size of the vector: vector<int> a; // size is 0 a.resize(4); // now has 4 elements Use push_back to increase the size by one and add a new element to the end, pop_back removes the last element vector<int> a; a.push_back(25); // size is 0 // now has 1 element a.pop_back(); // now has 0 elements Implementation of resizing is handled internally 10 (presumably it is done efficiently). Parameter passing (for large objects) Multidimensional arrays Call by value is the default int findmax(vector<int> a); Problem: lots of copying if a is large Call by reference can be used int findmax(vector<int> & a); Problem: may still want to prevent changes to a Call by constant reference: int findmax(const vector<int> & a); the const won t allow a to be changed 11 multidimensional array: an array that is accessed by more than one index int table[2][5]; // 2 rows, 5 columns table[0][0] = 10; // puts 10 in upper left There are no first-class versions of this in the STL The book defines one (ch 3) called a matrix. The primitive version can have more than 2 dimensions. 12

Pointers Pointers Pointer: an variable that stores the address of another variable, providing indirect access to it. The address operator (&) returns the address of a variable. int x; cout << &x << endl; // 0xbffffb0c An asterisk is used to define a pointer variable int *ptr; ptr is a pointer to an int. It can contain addresses of int variables. ptr = &x; 13 The unary operator * is the dereferencing operator. *ptr is an alias for the variable that ptr points to. int *ptr; //declaration, NOT dereferencing ptr = &x; //ptr gets the address of x *ptr = 7; //the thing ptr pts to gets 7 Initialization: //declaration, NOT dereferencing ptr is a pointer to an int, and it is initialized to the 14 address of x. Pointers: watchout Pointers: watchout What is wrong with each of the following? What is wrong with each of the following? int *ptr = x; int *ptr = x; x is not declared yet x is not an address int y = 99; int *ptr = &y; *ptr = x; ptr = &x; int y = 99; int *ptr = &y; *ptr = x; ptr = &x; y gets 10 (changes y) ptr points to x (changes ptr) 15 16

Pointers: More examples Pointers: More examples What is happening in each of the following? What is happening in each of the following? int *ptr = NULL; *ptr += 5; *ptr++; int *ptr = NULL; *ptr += 5; *ptr++; changes x to 15 sets ptr to 0 (null ptr) changes ptr to point to location after x (returns its value) int x = 10, y = 99; int *ptr1 = &x, *ptr2 = &y; int x = 10, y = 99; int *ptr1 = &x, *ptr2 = &y; ptr1 = ptr2; *ptr1 = *ptr2; if (ptr1==ptr2)... if (*ptr1==*ptr2)... 17 ptr1 = ptr2; *ptr1 = *ptr2; if (ptr1==ptr2)... if (*ptr1==*ptr2)... makes ptr1 pt to what ptr2 pts to copies what ptr2 points to into the location ptr1 points to do the ptrs point to the same location? 18 do the ptrs point to the same values? Dynamic Memory Allocation Dynamic Memory Allocation: delete Automatic variables: an variable that are created when declared, and destroyed at the end of their scope. Dynamic memory allocation allows you to create and destroy variables on demand, during run-time. new operator requests dynamically allocated memory and returns address of newly created anonymous variable. string *ptr; ptr = new string( hello ); cout << *ptr << endl; 19 20 cout << Length: << (*ptr).size() << endl; When you are finished using a variable created with new, use the delete operator to destroy it. int *ptr; ptr = new int; *ptr = 100;... delete ptr; Do not delete pointers whose values were NOT dynamically allocated using new. Do not forget to delete dynamically allocated variables (memory leaks: allocated but inaccessible memory).

Structures Structures: operations A structure stores a collection of objects of various types Each object in the structure is a member, and is accessed using the dot member operator. struct Student { int idnumber; string name; int age; string major; }; Student student1, student2; student1.name = John Smith ; Defines a new data type Defines new variables 21 Valid operations over entire structs: assignment: student1 = student2; function call: myfunc(gradstudent,x); Invalid operations over structs: comparison: student1 == student2 output: cout << student1; input: cin >> student2; Must do these member by member 22 Pointers to structures Indigenous vs exogenous data We can define pointers to structures Consider two structure definitions: Student s1 = {12345, Jane Doe, 18, Math }; Student *ptr = &s1; To access the members via the pointer: cout << *ptr.name << end; dot operator has higher precedence, so use (): cout << (*ptr).name << end; or equivalently, use ->: cout << ptr->name << end; // ERROR: *(ptr.name) 23 struct Student { int idnumber; string name; int age; string major; }; struct Teacher { int idnumber; string *name; }; indigenous data: completely contained within the structure all Students members exogenous data: reside outside the structure, and are pointed to from the structure. Teacher s name 24

Shallow copy vs deep copy Shallow copy vs deep copy Consider structure assignment: Student s1, s2;... s1 = s2; Teacher t1, t2;... t1 = t2; By default, it is member by member copy. This is fine for Student, but not the Teachers t1.name and t2.name share the same memory, point to the same place. delete t1.name; will make t2.name invalid. Shallow copy: copies top level data only. For pointers, the address is copied, not the values pointed to. This is the default Deep copy: copies the pointed at values instead of their addresses. Requires allocating new memory. Same concepts apply to comparisons. 25 26