Lecture 05 POINTERS 1

Similar documents
Chapter 6 - Pointers

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

MYcsvtu Notes LECTURE 34. POINTERS

C Pointers Pearson Education, Inc. All rights reserved.

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Pointers and Strings. Adhi Harmoko S, M.Komp

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

Fundamentals of Programming Session 20

C++ Programming Chapter 7 Pointers

by Pearson Education, Inc. All Rights Reserved.

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

C Pointers. 7.2 Pointer Variable Definitions and Initialization

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

Programming for Engineers Pointers

Lecture 9 - Pointers 1

Lecture 4. Default Arguments. Set defaults in function prototype. int myfunction( int x = 1, int y = 2, int z = 3 );

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

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

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

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Relationship between Pointers and Arrays

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

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

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Pointers in C. Recap: Anatomy of a Typical C Program. declarations variables functions. int main (void){ declarations; statements; return value; }

IS 0020 Program Design and Software Tools

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

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

CSC 211 Intermediate Programming. Arrays & Pointers

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

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

Week 3: Pointers (Part 2)

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

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

Chapter 7 C Pointers

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

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

Fundamentals of Programming Session 20

0 vs NULL // BBM 101. Introduction to Programming I. Lecture #12 C Pointers & Strings

Lecture 09X: C Func/on Pointers Concurrent and Mul/core Programming

What is an algorithm?

Pointers. Memory. void foo() { }//return

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

Fundamental of Programming (C)

Functions. Introduction :

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

More Pointers Week 11

BITG 1113: POINTER LECTURE 12

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

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

Pointers, Dynamic Data, and Reference Types

Pointers. 10/5/07 Pointers 1

ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers

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

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

Lab 3. Pointers Programming Lab (Using C) XU Silei

Visual C# Instructor s Manual Table of Contents

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Content. In this chapter, you will learn:

Introduction to Computer Science Midterm 3 Fall, Points

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Lecture 23: Pointer Arithmetic

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

PROGRAMMAZIONE I A.A. 2017/2018

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

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

C Pointers. 6th April 2017 Giulio Picierro

Fundamentals of Programming Session 19

Variables and Operators 2/20/01 Lecture #

Binghamton University. CS-211 Fall Pointers vs. Arrays

[0569] p 0318 garbage

Using pointers with functions

... Lecture 12. Pointers

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

OBJECT ORIENTED PROGRAMMING USING C++

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Review of the C Programming Language for Principles of Operating Systems

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

Pointers in C/C++ 1 Memory Addresses 2

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Goals of this Lecture

Pointers as Arguments

Binghamton University. CS-211 Fall Pointers

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Fundamentals of Programming Session 19

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.

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Week 7: Pointers and Arrays. BJ Furman 02OCT2009

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Computer Programming C++ (wg) CCOs

12. Pointers Address-of operator (&)

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Review of the C Programming Language

Tutorial 10 Pointers in C. Shuyue Hu

Binghamton University. CS-211 Fall Pointers

Transcription:

Lecture 05 POINTERS 1

Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings

Pointer Variable vs. Normal Variable Normal variables contain a specific value (direct count reference) Pointer variables Contain memory addresses as their values Pointers contain address of a variable that has a countptr specific value (indirect reference) Indirection - referencing a pointer value 7 count 7

Declarations and Initialization Pointer declarations * used with pointer variables int *myptr; Declares a pointer to an int (pointer of type int *) Multiple pointers, multiple * int *myptr1, *myptr2; Can declare pointers to any data type Initialize pointers to 0, NULL, or an address 0 or NULL - points to nothing (NULL preferred)

& (address operator) Pointer Operators Returns address of operand int y = 5; int *yptr; yptr = &y; //yptr gets address of y yptr points to y yptr y 5 yptr 500000 600000 y 600000 5 Address of y is value of yptr

Pointer Operators * (indirection/dereferencing operator) Returns a synonym/alias of what its operand points to *yptr returns y (because yptr points to y) * can be used for assignment Returns alias to an object *yptr = 7; // changes y to 7

Pointer Operators * and & are inverses They cancel each other out *&yptr -> * (&yptr) -> * (address of yptr)-> returns alias of what operand points to -> yptr &*yptr -> &(*yptr) -> &(y) -> returns address of y, which is yptr -> yptr

The address of a is the value of aptr. The * operator returns an alias to what its operand points to. aptr points to a, so *aptr returns a. Notice how * and & are inverses

Calling Functions by Reference Call by reference with pointer arguments Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a pointer * operator Used as alias/nickname for variable inside of function void double(int *number) { } *number = 2 * (*number); *number used as nickname for the variable passed

Notice how the address of number is given - cubebyreference expects a pointer (an address of a variable). Inside cubebyreference, *nptr is used (*nptr is number).

Using the Const Qualifier with Pointers const qualifier - variable cannot be changed Good idea to have const if function does not need to change a variable Attempting to change a const is a compiler error const pointers - point to same memory location Must be initialized when declared int *const myptr = &x; Type int *const - constant pointer to an int const int *myptr = &x; Regular pointer to a const int const int *const Ptr = &x; const pointer to a const int

Changing *ptr is allowed - x is not a constant. Changing ptr is an error - ptr is a constant pointer. FIG07_13.c: Error E2024 FIG07_13.c 16: Cannot modify a const object in function main *** 1 errors in Compile ***

Swap function Using Call-by-reference Implement swap function Swap two elements swap function must receive address (using &) of array elements Array elements have call-by-value default Using pointers and the * operator, swap can switch array elements

Pointer Expressions and Pointer Arithmetic Arithmetic operations can be performed on pointers Increment/decrement pointer (++ or --) Add an integer to a pointer( + or +=, - or -=) Pointers may be subtracted from each other Operations meaningless unless performed on an array

Pointer Expressions and Pointer Arithmetic 5 element int array on machine with 4 byte ints vptr points to first element v[0] at location 3000. (vptr = 3000) vptr +=2; sets vptr to 3008 vptr points to v[2] (incremented by 2), but machine has 4 byte ints. location 3000 3004 3008 3012 3016 Unit is byte v[0] v[1] v[2] v[3] v[4] pointer variable vptr

Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns number of elements from one to the other. vptr2 = v[2]; vptr = v[0]; vptr2 - vptr == 2. Pointer comparison ( <, ==, > ) See which pointer points to the higher numbered array element Also, see if a pointer points to 0

Pointer Expressions and Pointer Arithmetic Pointers of the same type can be assigned to each other If not the same type, a cast operator must be used Exception: pointer to void (type void *) Generic pointer, represents any type No casting needed to convert a pointer to void pointer void pointers cannot be dereferenced

The Relationship Between Pointers and Arrays Arrays and pointers closely related Array name like a constant pointer Pointers can do array subscripting operations Declare an array b[5] and a pointer bptr bptr = b; Array name actually a address of first element OR bptr = &b[0] Explicitly assign bptr to address of first element

The Relationship Between Pointers and Arrays Element b[n] can be accessed by *( bptr + n ) n - offset (pointer/offset notation) Array itself can use pointer arithmetic. b[3] same as *(b + 3) Pointers can be subscripted (pointer/subscript notation) bptr[3] same as b[3]

Arrays of Pointers Arrays can contain pointers - array of strings char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades" }; String: pointer to first character char * - each element of suit is a pointer to a char Strings not actually in array - only pointers to string in array suit[0] H e a r t s \0 suit[1] suit[2] suit[3] D i a m o n d s \0 C l u b s \0 S p a d e s \0 suit array has a fixed size, but strings can be of any size.

Case Study: A Card Shuffling and Dealing Simulation Card shuffling program Use array of pointers to strings Use double scripted array (suit, face) The numbers 1-52 go into the array - this is the order they are dealt

Case Study: A Card Shuffling and Dealing Simulation

The numbers 1-52 are randomly placed into the deck array. 3. Define functions Searches deck for the card number, then prints the face and suit.

Pointers to Functions Pointer to function Contains address of function Similar to how array name is address of first element Function name is starting address of code that defines function Function pointers can be Passed to functions Stored in arrays Assigned to other function pointers

Pointers to Functions Example: bubblesort Function bubble takes a function pointer bubble calls this helper function this determines ascending or descending sorting The argument in bubblesort for the function pointer: bool ( *compare )( int, int ) tells bubblesort to expect a pointer to a function that takes two ints and returns a bool. If the parentheses were left out: bool *compare( int, int ) Declares a function that receives two integers and returns a pointer to a bool

Notice the function pointer parameter. 1. Initialize array. 2. Prompt for ascending or descending sorting. 2.1 Put appropriate function pointer into bubblesort. 2.2 Call bubble. 3. Print results.

ascending and descending return true or false. bubble calls swap if the function call returns true. Notice how function pointers are called using the dereferencing operator. The * is not required, but emphasizes that compare is a function pointer and not a function.

65int ascending( int a, int b ) 66{ 67 return b < a; /* swap if b is less than a */ 68} 69 70int descending( int a, int b ) 71{ 72 return b > a; /* swap if b is greater than 73} a */