COSC 220 Computer Science II

Slides:



Advertisements
Similar presentations
Kernighan/Ritchie: Kelley/Pohl:
Advertisements

Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
Arrays and Pointers in C Alan L. Cox
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
C++ Loose ends from last time. Variable initialization You can do the usual things int x; x = 10; int y = 20; And you can do an unusual thing int x(10);
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Homework due Test the random number generator Create a 1D array of n ints Fill the array with random numbers between 0 and 100 Compute and report the average.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Lecture 7: Arrays BJ Furman 06OCT2012. The Plan for Today Announcements Review of variables and memory Arrays  What is an array?  How do you declare.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Chapter VII: Arrays.
Arrays.
Week 2 - Wednesday CS 121.
EGR 2261 Unit 11 Pointers and Dynamic Variables
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Chapter 8 Arrays, Strings and Pointers
EGR 2261 Unit 10 Two-dimensional Arrays
Chapter 9: Pointers.
Motivation and Overview
Hassan Khosravi / Geoffrey Tien
© 2016 Pearson Education, Ltd. All rights reserved.
Pointers.
New Structure Recall “average.cpp” program
Student Book An Introduction
Programmazione I a.a. 2017/2018.
Lecture 6 C++ Programming
Introduction to Pointers
Introduction to Pointers
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Arrays An Array is an ordered collection of variables
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 9: Pointers.
CMSC202 Computer Science II for Majors Lecture 04 – Pointers
Arrays Kingdom of Saudi Arabia
Pointers.
Beginning C for Engineers
Pointers.
Chapter 16 Pointers and Arrays
Overloading functions
Dr Tripty Singh Arrays.
CS150 Introduction to Computer Science 1
Data Structures and Algorithms Introduction to Pointers
CS250 Introduction to Computer Science II
Data Structures & Algorithms
Chapter 9: Pointers and String
Arrays 2-May-19.
Assignment due Write a program the generates a random integer expression, presents the two operands and the result to the user, and asks the user to tell.
CISC181 Introduction to Computer Science Dr
EECE.2160 ECE Application Programming
Introduction to Pointers
Pointers and pointer applications
Week 7 - Friday CS222.
SPL – PS2 C++ Memory Handling.
Introduction to Pointers
Presentation transcript:

COSC 220 Computer Science II Lecturer: Dr. Joseph Anderson Office: 140 Devilbiss Hall Office Hours: Monday 9-11am, Wednesday 2-4pm, Friday 10-11am

Course information Website Canvas http://faculty.salisbury.edu/~jtanderson/teaching/cosc220/au17/index.html Syllabus Schedule Canvas Duplicates of materials found on website Updated less periodically

Course overview Study more advanced problem-solving techniques with programming in C++ Become familiar with low-level development tools Command-line interface GCC will be used for compiling code How linking source and header files actually happens Linux environment Will begin using in the first lab

How to succeed Come to class Come to labs Review text before/after each lecture Contains many small pieces of information that may not be covered in class or on exams, but can be useful later Experiment! If I try and write a program to do X, what will happen? Do it and find out! What if… Do it! What happened? Why? (Computer) Science

If you get stuck Stop. Don’t try and multitask Change tasks, go eat, exercise, etc. Try again, back up to an earlier point Ask for help Having time to do this means start early enough to find problems!

CLI Development In addition to advanced C++ we will be using very low-level development tools Command line compilation and linking Pure text-based editing Linux filesystem and tools See webpage for helpful links Code editors Linux references

Review: arrays An array is a special data type that holds multiple values, of some other data type The data it holds can also be an array type! What does this mean? An array of arrays, or multidimensional array!

Array review Array declaration: int my_array[10]; const int my_size = 10; char my_word[my_size]; int my_array[] = {1, 2, 3, 4}; int my_array[5] = {1, 2, 3, 4}; // what is different? Array size must be constant, integer, bigger than zero Or, as above, implicit from an array literal

Array review What happens when an array is declared? The compiler looks at 1) the type and 2) the size Allocates a block of memory of (type size) * (array size) bytes E.g. the ‘char’ type (usually) takes 1 byte of space, so an array of 10 char’s would take 10 bytes of memory E.g. an array of 10 doubles, which are 8 bytes each, would take 80 bytes of memory Consider the declaration: double prices[6];

Array REview Accessing an array Use the [] operator E.g. int my_array[10]; my_array[3] = 5; int a = my_array[3]; Calling my_array[n] tells the compiler to access n*size bytes beyond the head of the array

Array review Caveats In C++, array indexing starts at 0 An n element array has indexes 0 through n-1 C++ provides no access verification The following is legal: int arr[3] = {1,2,3}; int b = arr[3]; // looks ok, but really not The compiler will access the head of the array plus 12 bytes But the array is only 12 bytes long!

Array review Making sure your array access is safe Use variable to store size Use the size variable in loop iteration const int NUM_WEEKS = 52; int weeks[NUM_WEEKS]; // ... Code to populate the weeks array for(i=0; i < NUM_WEEKS; i++){ printf(“Checking week %d”, weeks[i]); }

Off-by-one Errors Consider: Does it compile? Does it work? const int NUM_WEEKS = 52; int weeks[NUM_WEEKS]; // ... Code to populate the weeks array for(i=0; i <= NUM_WEEKS; i++){ printf(“Checking week %d”, weeks[i]); } Does it compile? Does it work?

Advanced for-loop on Array C++11 introduces an easier and safer way to iterate: range-based for loops int days[5] = {2,4,6,8,10}; for( int val : days ){ printf(“%d”, val); } Will print: 2 4 6 8 10

Ranged-based for loops Useful when you don’t need to know the index of the element Can be used with reference variables to modify array elements We will see more later, when working with pointers Still have to know the length of the array in advance Fortunately, there are techniques one can use to change the maximum length of an array during execution of a program We will see how to do this with pointers

Multidimensional arrays The general form of an array definition is dataType name[]; What if we wanted to track two different indexes (e.g. a matrix of data): 1 2 3 4 5 6 7 8 9 10 C++ Allows us to declare an array which takes two (or more) index parameters int myMatrix[2][5] = {{1,2,3,4,5}, {6,7,8,9,10}}; We can think of this as an “array of arrays” First index is the “row” and second is the “column” Can read the definition as “two arrays, each with five elements” Referencing myMatrix[1][3] would return 9, as we referenced the fourth element of the second array.

Variable addresses Recall that every variable in C++ is really just a reference to a memory location, along with type information about the data contained there Sometimes we may want to access the actual address where the data is stored char letter; int day; double price; For the above, we know that there are segments of memory 1 byte, 2 bytes, and 8 bytes long, respectively But we don’t know where! In C++ (not Java) we can find out!

pointers We have a simple operator for retrieving the location in memory The address operator: & It is a unary operator (takes only one argument, similar to ++ and --) The type of a pointer is (Type*) where “Type” is the type that it points to int a = 10; int* b = &a; // The “type” of data returned by &a is “int*” printf(“%d”,sizeof(a)); // prints “4” on most systems printf(“%d”,sizeof(b)); // prints “8” on a 64-bit system

Pointer dereference If you have a pointer, ptr1, how to access the variable it points to? Use the * (dereference) operator int a = 10; int *ptr = &a; int b = *ptr; // b == 10 printf(“%d”,*ptr); printf(“%d”,b);

Arrays as Function Parameters Recall that we can use an array as a parameter to a function: void printArray(int my_arr[], int size){ for( int i=0; i < size; i++){ printf(“%d\n”,my_arr[i]); } What is actually passed is a pointer to the start of the array

Pointers as parameters Recall: reference variables int my_age; void askForAge(int &age){ std::cout << “What is your age?\n” << std::endl; std::cin >> age; } Calling askForAge(my_age) would store the response in the variable without any extra work (you would still want to validate)

Null pointers When you declare a pointer, you should always initialize it If you don’t know what the first value should be, set it to 0, or the null pointer int *ptr = nullptr; // Use 0 or NULL if not in C++11 standard If by accident, you accessed the memory referenced by an uninitialized pointer, you could end up modifying memory you don’t mean to Because when the pointer is declared, it’s contents aren’t changed, so it could contain data that coincidentally is the address of a part of memory being used for something else!

Pointer comparison Pointers refer to addresses As such, you can compare with < > == != >= <= ptr1 < ptr2 Compares the position in memory *ptr1 < *ptr2 Compares the values pointed to, if they can be compared

Pointer arithmetic As we saw before, the [i] operation really just says “the beginning of the array plus i more elements” This is just calculated as “my_arr + i*sizeof(int)” But C++ is smart enough so that you don’t need sizeof above: *(my_arr + i) Gives same as my_arr[i]