Week 4. Pointers and Addresses. Dereferencing and initializing. Pointers as Function Parameters. Pointers & Structs. Gaddis: Chapters 9, 11

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

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Structures. Data Types Structures. Data Types (C/C++) Gaddis: A Data Type consists of: Unit 7. example: Integer. CS 1428 Spring 2018

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

Overloading Operators

Functions, Arrays & Structs

Ch 11. Structured Data (11.2 to 11.8) Data Types Structures. Data Types (C/C++) Data Type: CS 2308 Fall example: Integer.

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-3,5

l A set is a collection of objects of the same l {6,9,11,-5} and {11,9,6,-5} are equivalent. l There is no first element, and no successor of 9.

Functions, Arrays & Structs

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-4,6

Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7

l A set is a collection of objects of the same l {6,9,11,-5} and {11,9,6,-5} are equivalent. l There is no first element, and no successor of 9.

Straight-line code (or IPO: Input-Process-Output) If/else & switch. Relational Expressions. Decisions. Sections 4.1-6, , 4.

Introduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18

Data Types (C/C++) Structures

Pointer Variables. Pointers, Structures and Arrays. Schematics Example. Pointer Schematics

BITG 1113: POINTER LECTURE 12

l Tree: set of nodes and directed edges l Parent: source node of directed edge l Child: terminal node of directed edge

l A program is a set of instructions that the l It must be translated l Variable: portion of memory that stores a value char

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

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

3.1 The cin Object. Expressions & I/O. Console Input. Example program using cin. Unit 2. Sections 2.14, , 5.1, CS 1428 Spring 2018

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

What is an algorithm?

FORM 2 (Please put your name and form # on the scantron!!!!)

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

MYcsvtu Notes LECTURE 34. POINTERS

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

CS201- Introduction to Programming Current Quizzes

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

PROGRAMMAZIONE I A.A. 2017/2018


CSC 215 Structures. Dr. Achraf El Allali

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Quiz 0 Review Session. October 13th, 2014

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

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

Pointers. Variable Declaration. Chapter 10

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

Pointers and Dynamic Memory Allocation

Searching, Sorting & Analysis

Dynamic Allocation of Memory

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Pointers, Dynamic Data, and Reference Types

C++ Programming Chapter 7 Pointers

Structured Data. CIS 15 : Spring 2007

MEMORY ADDRESS _ REPRESENTATION OF BYTES AND ITS ADDRESSES

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

1 Short Answer (5 Points Each)

Outerjoins, Constraints, Triggers

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CSC 211 Intermediate Programming. Arrays & Pointers

Homework #3 CS2255 Fall 2012

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

CS 11 C track: lecture 5

! 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)

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

REFERENCES, POINTERS AND STRUCTS

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

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

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CS 11 C track: lecture 6

Pointers! Arizona State University 1

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Strings Prentice Hall, Inc. All rights reserved.

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

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8

Introduction to Scientific Computing and Problem Solving

C++ for Java Programmers

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Hardware Components Illustrated

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointer Data Type and Pointer Variables

CSC1322 Object-Oriented Programming Concepts

Unit IV & V Previous Papers 1 mark Answers

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Searching & Sorting. Definitions of Search and Sort. Other forms of Linear Search. Linear Search. Week 11. Gaddis: 8, 19.6,19.8.

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

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

by Pearson Education, Inc. All Rights Reserved.

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC


Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

SQL3 Objects. Lecture #20 Autumn, Fall, 2001, LRX

Searching & Sorting. Definitions of Search and Sort. Other forms of Linear Search. Linear Search. Week 11. Gaddis: 8, 19.6,19.8. CS 5301 Spring 2017

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.

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

Transcription:

Week 4 Pointers & Structs Gaddis: Chapters 9, 11 CS 5301 Spring 2017 Ji Seaman 1 Pointers and Addresses The address operator (&) returns the address of a variabe. int x; cout << &x << end; // 0xbffffb0c Pointer: a variabe that stores the address of another variabe, providing indirect access to it. An asterisk is used to define a pointer variabe int *ptr; ptr is a pointer to an int. It can contain addresses of int variabes. ptr = &x; 2 Dereferencing and initiaizing Pointers as Function Parameters The unary operator * is the dereferencing operator. *ptr is an aias for the variabe that ptr points to. int x = 10; int *ptr; //decaration, NOT dereferencing ptr = &x; //ptr gets the address of x *ptr = 7; //the thing ptr pts to gets 7 Initiaization: int x = 10; int *ptr = &x; //decaration, NOT dereferencing ptr is a pointer to an int, and it is initiaized to the 3 address of x. Use pointers to impement pass by reference. //prototype: void changeva(int *); void changeva (int *va) { *va = *va * 11; int main() { int x; cout << "Enter an int " << end; cin >> x; changeva(&x); cout << x << end; How is it different from using reference parameters? 4

Pointers and Arrays You can treat an array variabe as if it were a pointer to its first eement. int numbers[] = {10, 20, 30, 40, 50; cout << first: << numbers[0] << end; cout << first: << *numbers << end; cout << &(numbers[0]) << end; cout << numbers << end; Output: first: 10 first: 10 0xbffffb00 0xbffffb00 5 Pointer Arithmetic When you add a vaue n to a pointer, you are actuay adding n times the size of the data type being referenced by the pointer. int numbers[] = {10, 20, 30, 40, 50; // sizeof(int) is 4. // Let us assume numbers is stored at 0xbffffb00 // Then numbers+1 is reay 0xbffffb00 + 1*4, or 0xbffffb04 // And numbers+2 is reay 0xbffffb00 + 2*4, or 0xbffffb08 // And numbers+3 is reay 0xbffffb00 + 3*4, or 0xbffffb0c cout << second: << numbers[1] << end; cout << second: << *(numbers+1) << end; cout << "size: " << sizeof(int) << end; cout << numbers << end; cout << numbers+1 << end; Output: second: 20 second: 20 size: 4 0xbffffb00 0xbffffb04 Note: array[index] is equivaent to *(array + index) 6 Pointers and Arrays pointer operations * + can be used with array variabes. subscript operations: [ ] can be used with pointers. int ist[10]; cin >> *(ist+3); int ist[] = {1,2,3; int *ptr = ist; cout << ptr[2]; 7 Comparing Pointers pointers (addresses) maybe compared using the reationa operators: < <= > >= ==!= Exampes: int arr[25]; What is the difference? ptr1 < ptr2 *ptr1 < *ptr2 cout << (&arr[1] > &arr[0]) << end; cout << (arr == &arr[0]) << end; cout << (arr <= &arr[20]) << end; cout << (arr > arr+5) << end; 8

Dynamic Memory Aocation The new operator When a function is caed, memory for oca variabes is automaticay aocated. When a function exits, memory for oca variabes automaticay disappears. Must know ahead of time the maximum number of variabes you may need. Dynamic Memory aocation aows your program to create variabes on demand, during run-time. 9 new operator requests dynamicay aocated memory for a certain data type: int *iptr; iptr = new int; new operator returns address of newy created anonymous variabe. use dereferencing operator to access it: *iptr = 11; cin >> *iptr; int vaue = *iptr / 3; 10 Dynamicay aocated arrays deete! dynamicay aocate arrays with new: int *iptr; //for dynamicay aocated array int size; cout << Enter number of ints: ; cin >> size; iptr = new int[size]; for (int i=1; i<size; i++) { iptr[i] = i; Program wi throw an exception and terminate if not enough memory avaiabe to aocate 11 When you are finished using a variabe created with new, use the deete operator to destroy it: int *ptr; doube *array; ptr = new int; array = new doube[25];... deete ptr; deete [] array; // note [] required for dynamic arrays! Do not deete pointers whose vaues were NOT dynamicay aocated using new! Do not forget to deete dynamicay aocated variabes (Memory Leaks!!). 12

Returning Pointers from Functions functions may return pointers: The returned pointer must point to int * findzero (int arr[]) { int *ptr; ptr = arr; whie (*ptr!= 0) ptr++; return ptr; dynamicay aocated memory OR an item passed in via an argument NOTE: the return type of this function is (int *) or pointer to an int. NOTE: if the function returns dynamicay aocated memory, Returning Pointers from Functions: dupicatearray int *dupicatearray (int arr[], int size) { int *newarray; if (size <= 0) return NULL; int a [5] = {11, 22, 33, 44, 55; int *b = dupicatearray(a, 5); for (int i=0; i<5; i++) if (a[i] == b[i]) cout << i << ok << end; deete [] b; //caer deetes mem //size must be positive //NULL is 0, an invaid address newarray = new int [size]; //aocate new array for (int index = 0; index < size; index++) newarray[index] = arr[index]; //copy to new array return newarray; then it is the responsibiity of the caing function to deete it. 13 14 Output 0 ok 1 ok 2 ok 3 ok 4 ok Structures A structure stores a coection of objects of various types Each eement in the structure is a member, and is accessed using the dot member operator. struct Student { int idnumber; string name; int age; string major; ; Defines a new data type Student student1, student2; Defines new variabes student1.name = John Smith ; 15 Student student3 = {123456, Ann Page,22, Math ; Structures: operations Vaid operations over entire structs: assignment: student1 = student2; function ca: myfunc(gradstudent,x); Invaid operations over structs: comparison: student1 == student2 output: cout << student1; input: cin >> student2; void myfunc(student, int); //prototype Must do these member by member 16

Arrays of Structures Arrays of Structures: initiaization You can store vaues of structure types in arrays. Student roster[40]; //hods 40 Student structs Each student is accessibe via the subscript notation. roster[0] = student1; //copy student1 into 1st position Members of structure accessibe via dot notation cout << roster[0].name << end; To initiaize an array of structs: struct Student { int idnumber; string name; int age; string major; ; int main() { Student roster[] = { {123456,"Ann Page",22,"Math", {111222,"Jack Spade",18,"Physics" ; 17 18 Arrays of Structures Passing structures to functions Arrays of structures processed in oops: Student roster[40]; //input for (int i=0; i<40; i++) { cout << "Enter the name, age, idnumber and " << "major of the next student: \n"; cin >> roster[i].name >> roster[i].age >> roster[i].idnumber >> roster[i].major; //output a the id numbers and names for (int i=0; i<40; i++) { cout << roster[i].idnumber << end; cout << roster[i].name << end; Structure variabes may be passed as arguments to functions: void getstudent(student &s) { // pass by reference cout << "Enter the name, age, idnumber and " << "major of the student: \n"; cin >> s.name >> s.age >> s.idnumber >> s.major; void showstudent(student x) { cout << x.idnumber << end; cout << x.name << end; cout << x.age << end; cout << x.major << end; // in main: Student student1; getstudent(student1); showstudent(student1); 19 20

Pointers to structures Dynamicay Aocating Structures We can define pointers to structures Student s1 = {12345, Jane Doe, 18, Math ; Student *ptr = &s1; To access the members via the pointer: Structures can be dynamicay aocated with new: Student *sptr; sptr = new Student; sptr->name = Jane Doe ; sptr->idnum = 12345;... deete sptr; cout << *ptr.name << end; // ERROR: *(ptr.name) dot operator has higher precedence, so use (): cout << (*ptr).name << end; or equivaenty, use ->: cout << ptr->name << end; 21 Arrays of structures can aso be dynamicay aocated: Student *sptr; sptr = new Student[100]; sptr[0].name = John Deer ;... deete [] sptr; No arrows (->) necessary. It s just an array of Student 22